I am working on an app which contains an Android SQLite database. I add and delete rows in this database. When I delete my row, it is based on the ROWID. But I found out, that despite I delete the row, the ROWID remains. So for example if I have 3 rows in my database and delete the 2nd row, my third row will not change to 2 it remains 3. Then if I add a row, it will be 4.
So my question is, how to do that when I delete a row, and add a new one then the number of the added row would equal to the deleted row. So for example if I delete the first row, than the database will show me next to the other rows 1,2,3... and not 2,3,4...
Sorry, maybe it is a little bit complicated, but I hope it makes sense.
Here is my code:
public HotOrNot open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name, String hotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
public String getName(long l) throws SQLException{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String name = c.getString(1);
return name;
}
return null;
}
public String getHotness(long l) throws SQLException{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String hotness = c.getString(2);
return hotness;
}
return null;
}
public void updateEntry(long lRow, String mName, String mHotness) throws SQLException{
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_NAME, mName);
cvUpdate.put(KEY_HOTNESS, mHotness);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + lRow, null);
}
public void deleteEntry(long lRow1) throws SQLException{
// TODO Auto-generated method stub
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1, null);
}
}
I know that it can't be done using ROWID, because it is unique for each row.
Could you please write the code how to solve this problem, because I am beginner in Android and also in SQLite.
Thanks in advance
SQLite keeps track of the largest ROWID that a table has ever held
using the special SQLITE_SEQUENCE table.
You can update SQLITE_SEQUENCE table-
UPDATE SQLITE_SEQUENCE SET seq = <n> WHERE name = <table_name>
n is the rowid - 1
Similar question.
Related
I have this:
public void addNewNote(Note n) {
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE, n.getNote_title());
values.put(COLUMN_TEXT, n.getNote_text());
values.put(COLUMN_FK, n.getNote_ForeignKey()); //this column is integer type
values.put(COLUMN_PT, String.valueOf(n.getNote_PersonType())); //this column is char type
SQLiteDatabase db = this.getWritableDatabase();
db.insert("tbl_Notes",null, values);
}
as my add method, as I traced it, the record is added successfully. but when I try to get my note with below code, findNote always returns null and cnt is always 0.
public Note findNote(int note_id){
String query = "select * from tbl_Notes"; // where " + COLUMN_ID + " = " + note_id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
int cnt = cursor.getCount();
Note N = new Note();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
N.setNote_title(cursor.getString(1)); //title column
N.setNote_text(cursor.getString(2)); //text body column
N.setNote_ForeignKey(Integer.parseInt(cursor.getString(3))); //foreign key column
N.setNote_PersonType(cursor.getString(4).charAt(0)); //person type column
cursor.close();
}else {
N = null;
}
return N;
}
and here is my onClick which fires addNewNote:
Note myNote = new Note(
txt_Title.getText().toString(),
foreignKey,
personType,
txt_Body.getText().toString()
);
tbl_notes.addNewNote(myNote);
what am I doing wrong?!
I am going to fetch some rows with specific tag in android Sqlite.
The problems are
I got 15 with cursor.getCount(); but 13 rows retrieved.
the 13 rows just repeat last row data
here is my code
public ArrayList<HashMap<String, String>> getTodo(String tag) {
ArrayList<HashMap<String,String>> arList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> todo = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "
+ COLUMN_TAG + " = ?";
String[] args={tag};
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, args);
// Move to first row
cursor.moveToFirst();
System.out.println(cursor.getCount());
if (cursor.getCount() > 0) {
do {
todo.put(COLUMN_ID, cursor.getString(cursor.getColumnIndex(COLUMN_ID)));
todo.put(COLUMN_FROM, cursor.getString(cursor.getColumnIndex(COLUMN_FROM)));
todo.put(COLUMN_TO, cursor.getString(cursor.getColumnIndex(COLUMN_TO)));
todo.put(COLUMN_TITLE, cursor.getString(cursor.getColumnIndex(COLUMN_TITLE)));
todo.put(COLUMN_TAG, cursor.getString(cursor.getColumnIndex(COLUMN_TAG)));
arList.add(todo);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return todo
return arList;
}
Please help. Thanks
You are using the same todo object for all rows, so you end up with lots of references to the same object.
Create a new one for each row in the loop:
Cursor cursor = db.rawQuery(selectQuery, args);
try {
while (cursor.moveToNext()) {
HashMap<String, String> todo = new HashMap<String, String>();
todo.put(...);
...
arList.add(todo);
}
finally {
cursor.close();
}
It's better to make the todo's you want to acquire into objects
public class Todo {
public String id, from, to, title, tag;
//setters and getters (not necessary)
}
public ArrayList<MyData> getTodo(String tag) {
ArrayList<MyData> arList = new ArrayList<MyData>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "
+ COLUMN_TAG + " = ?";
String[] args={tag};
try {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, args);
// Move to first row
if (!cursor.moveToFirst())
return arList;
do {
Todo todo = new Todo();
todo.id = cursor.getString(cursor.getColumnIndex(COLUMN_ID));
todo.from = cursor.getString(cursor.getColumnIndex(COLUMN_FROM));
todo.to = cursor.getString(cursor.getColumnIndex(COLUMN_TO));
todo.title = cursor.getString(cursor.getColumnIndex(COLUMN_TITLE))
todo.tag = cursor.getString(cursor.getColumnIndex(COLUMN_TAG));
arList.add(todo);
} while(cursor.moveToNext());
cursor.close();
db.close();
return arList;
}
finally {
cursor.close();
db.close();
}
}
You keep putting new strings to an already created hashmap, but you keep using the same keys, and therefore, many entries get replaced. The Todo object keeps your code readable. You should also check if the cursor can jump to the first entry (which makes a getCount call unnecessary)
I would like to return a true / false value when the string match with the column of sqlite. How can I implement the search function?
How to use cursor to do searching?
public boolean searchLuggage(String code) {
ArrayList<String> luggageCheck = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
try {
Cursor cursor = db.query(true, TABLE_LUGGAGES, new String[] { your field list }, SearchColumnname + "='" + code + "'", null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
luggageCheck.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LUGGAGE_TABLE = "CREATE TABLE " + TABLE_LUGGAGES + "(" + KEY_NAME + " TEXT NOT NULL," + KEY_CODE + " TEXT NOT NULL," + KEY_NUMBER + " TEXT NOT NULL );";
db.execSQL(CREATE_LUGGAGE_TABLE);
}
Replace this
Cursor cursor = db.query(true, TABLE_LUGGAGES, new String[] { your field list }, SearchColumnname + "='" + code + "'", null, null, null, null, null);
with this
Cursor cursor = db.query(true, TABLE_LUGGAGES, null, SearchColumnname + "= ?", new String[] { code }, null, null, null, null);
I'm trying to retrieve the data of a particulate row in a sqlite database . and trying to display it to on a EditText but I'm getting this error , Kindly help me in solving the error !
Thanks in advance :)
here is the logcat data showing error
12-31 22:28:17.731: E/2.4(12285): 111111
12-31 22:28:17.741: E/2.5(12285): 111111
12-31 22:28:17.771: E/SQLiteLog(12285): (1) no such column: _id10
12-31 22:28:17.791: D/AndroidRuntime(12285): Shutting down VM
here is the code : ( of the function getName , which is being used to retrieve the data of column 1 ) [getting error after log.e("2.5".... ) ]
public String getName(long l) {
// TODO Auto-generated method stub
Log.e("2.4","111111");
String[] column = new String[]{KEY_ROWID, KEY_NAME, KEY_HOTNESS };
Log.e("2.5","111111");
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Log.e("2.6","111111");
if(c != null)
{
Log.e("2.7","111111");
c.moveToFirst();
Log.e("2.8","111111");
String name = c.getString(1);
Log.e("2.9","111111");
return name;
}
return null;
}
public String getHotness(long l)
{
Log.e("3.1","111111");
// TODO Auto-generated method stub
String[] column = new String[]{KEY_ROWID, KEY_NAME, KEY_HOTNESS };
Log.e("3.2","111111");
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Log.e("3.3","111111");
if(c != null)
{
Log.e("3.4","111111");
c.moveToFirst();
Log.e("3.5","111111");
String hotness = c.getString(2);
Log.e("3.6","111111");
return hotness;
}
return null;
}
And is the code of the activity which is calling this function
case R.id.bgetInfo:
String s = sqlRow.getText().toString();
long l = Long.parseLong(s);
HotOrNot hon = new HotOrNot(this);
hon.open();
String returnedName = hon.getName(l);
String returnedHotness = hon.getHotness(l);
hon.close();
Log.e("1.2","111111");
sqlName.setText(returnedName);
Log.e("1.3","111111");
sqlHotness.setText(returnedHotness);
Log.e("1.4","111111");
break;
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
I have an SQLite database in an Android app. One database with two tables. simple read in some text and read it out, however, the first of two tables works perfectly and the second table does not and gives errors. I have looked at my code and it seems all correct. I dare anyone to find an error in my code or SQL statements below.
Especially interested in the SQL statements, because my SQL code is PERFECT as far as I know, for both tables, however in the LOGCAT says that a there is no table that I am reading into for table two.
Why would one of my tables work and the other not? Yet they are in the same database and written the same way.
DATABASE OPERATION ON FIRST TABLE; (WORKS PERFECTLY)
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HITS, hits);
ourDatabase.insert(DATABASE_TABLE_1, null, cv);
public String getData() {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_HITS };
Cursor c = ourDatabase.query(DATABASE_TABLE_1, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHits = c.getColumnIndex(KEY_HITS);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iName)
+ " " + c.getString(iHits) + "\n";
}
return result;
}
ourHelper.close();
DATABASE OPERATION ON SECOND TABLE; (DOES NOT WORK, ERRORS)
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put( KEY_RESULT, result);
return ourDatabase.insert(DATABASE_TABLE_2, null, cv);
public String getData2() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_RESULT, KEY_TABLET, KEY_DATE };
Cursor c = ourDatabase.query(DATABASE_TABLE_2, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iResult = c.getColumnIndex(KEY_RESULT);
int iTablet = c.getColumnIndex(KEY_TABLET);
int iDate = c.getColumnIndex(KEY_DATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iResult)
+ " " + c.getString(iTablet) + " " + c.getString(iDate) + "\n";
}
return result;
}
ourHelper.close();
LOGCAT OUTPUT;
01-31 19:33:01.670: E/AndroidRuntime(6420): FATAL EXCEPTION: main
01-31 19:33:01.670: E/AndroidRuntime(6420):
java.lang.RuntimeException: Unable to start activity ComponentInfo{DBView}:
android.database.sqlite.SQLiteException: no such column: date: , while compiling:
SELECT _id, game_result, tablet_winner, date FROM prizeTable
MORE CODE FOR DETAILS;
public class PlayGame {
public static final String KEY_ROWID="_id";
// for table 1 gameTable
public static final String KEY_NAME="persons_name";
public static final String KEY_HITS="persons_hits";
// for table 2 prizesTable
public static final String KEY_RESULT="game_result";
public static final String KEY_TABLET="tablet_winner";
public static final String KEY_DATE="date";
private static final String DATABASE_NAME="PlayGamesdb";
private static final String DATABASE_TABLE_1="gameTable";
private static final String DATABASE_TABLE_2="prizeTable";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_TABLE_1 = "CREATE TABLE " + DATABASE_TABLE_1 + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME + " TEXT NOT NULL, " + KEY_HITS + " TEXT NOT NULL);";
private static final String CREATE_TABLE_2 = "CREATE TABLE " + DATABASE_TABLE_2 + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_RESULT + " TEXT NOT NULL, " + KEY_TABLET
+ " TEXT NOT NULL, " + KEY_DATE + "TEXT NOT NULL);";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_1);
db.execSQL(CREATE_TABLE_2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_1 + "AND" + DATABASE_TABLE_2);
onCreate(db);
}
}
<<< EDIT >>>
Safime's suggestion fixed the crashing, that was adding a space between KEY_DATE and TEXT in the creation of the second table.
However still a problem, no more crashing, but the insert() method is still not working. Getting a -1 return shows that it is not inserting anything, and the the table 2 is still empty after inserting a new row to the table. Got to find out why it is failing to create any new rows in the table. Just like earlier, table one works fine but table two is still not working yet.
You are using Constraint NOT NULL and you are inserting only in one column. You must be getting SQLiteConstraintexception Exception. Try inserting in all columns.
You are missing an empty space after the column KEY_DATE and before TEXT on the creation of the second table.
(...) + KEY_DATE + " TEXT NOT NULL); (...)
Probably you have a problem at the create table statement of your second table. Try to open your db file with the sqlite3 command line tool, and see if this table exits. If not, the problem is in the CREATE statement.