This is my first attempt to write/read to a database using Android and SQLite.
The code below appears to be inserting data (I can see an increment in number of rows) but when I try to call the value, an exception is thrown
E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 6 rows, 2 columns.
I can't see why the below is failing.
public void Save(String name, String email) {
_db.execSQL("CREATE TABLE IF NOT EXISTS MailingList (Email VARCHAR, Name VARCHAR);");
_db.execSQL("INSERT INTO MailingList (Email, Name) VALUES('" + email + "', '" + name + "');");
ReadDatabase();
_db.close();
//_db.deleteAll();
}
private void ReadDatabase() {
Cursor cursor = _db.rawQuery("SELECT * FROM MailingList", null);
int i = cursor.getCount();
ArrayList<String> results = new ArrayList<String>();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("Name")); //ERROR
String email = cursor.getString(cursor.getColumnIndex("Email"));
results.add("Name: " + name + ", Email: " + email);
} while (cursor.moveToNext());
}
}
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(new ArrayAdapter<String>(this, R.layout.item_layout, results));
}
LogCat
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:435)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at com.lmsites.dave.lifecrymailinglist.MyActivity.ReadDatabase(MyActivity.java:106)
at com.lmsites.dave.lifecrymailinglist.MyActivity.Save(MyActivity.java:88)
at com.lmsites.dave.lifecrymailinglist.MyActivity.SaveClick(MyActivity.java:73)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3830)
at android.view.View.performClick(View.java:4450)
at android.view.View$PerformClick.run(View.java:18600)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5026)
at java.lang.reflect.Method.invokeNative(Native Method)
E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 6 rows, 2 columns.
This error indicates that you were trying to get the column index of a column which does not exist. getColumnIndex() returns -1 when it cannot find the specific column. I don't see any error in your code so I think there might be something wrong with the database itself.
When developing you have to remember that the SQLite database is only really deleted when you uninstall the app or wipe all data in the application manager.
So if you at some point made a mistake in an sql script or you added, removed or renamed some columns you need to uninstall and then reinstall the app for those changes to take effect in the database.
This of course is a problem for many apps and when developing you are going to run into this all the time. But as soon as your app is in the app store people are going to use it and you cannot ask everyone to reinstall your app every time you update it. That would be the ridiculous and people aren't going to like it, but there is a way around this.
You need to pass a version number into your SQLiteOpenHelper. Increase this version number every time you change something about the database and then when Android notices that the database version has increased the onUpgrade() callback will be called to upgrade your database accordingly! Try something like this:
public class ExampleSQLiteOpenHelper extends SQLiteOpenHelper {
public ExampleSQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// The create query here always has to be for the most up to
// date version of the database
db.execSQL("CREATE TABLE MailingList (Email VARCHAR, Name VARCHAR, PhoneNumber VARCHAR);");
db.execSQL("CREATE TABLE SomeTable (_id PRIMARY KEY AUTOINCREMENT, SomeColumn VARCHAR)");
...
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This will be called when you are starting your app for the first time
// after increasing the version number.
// This loops through all the version between the current version of
// the database and the newest version. upgradeTo is called with each
// version in between.
for(int i = oldVersion + 1; i <= newVersion; i++) {
upgradeTo(db, i);
}
}
private void upgradeTo(SQLiteDatabase db, int version) {
// With this switch you can execute the upgrade scripts for each version
// of the databse
switch (version) {
case 2:
// in this version we added a new column to MailingList so we
// use ALTER TABLE to add the new column
db.execSQL("ALTER TABLE MailingList ADD COLUMN PhoneNumber VARCHAR");
break;
case 3:
// In this version we added a new table
db.execSQL("CREATE TABLE SomeTable (_id PRIMARY KEY AUTOINCREMENT, SomeColumn VARCHAR)");
break;
case 4:
...
break;
case 5:
...
break;
}
}
}
The simplest solution of course is to drop all tables and recreate them in onUpgrade but than all the data in the database is lost. If you don't want that you can use something like the code above to gradually upgrade your database!
Related
I am making a db in Sqlite on android studio.
this is my code:
#Override
public void onCreate(#NotNull SQLiteDatabase db) {
//SQL - Structured Query Language
String CREATE_DATA_TIME_TABLE = "CREATE TABLE " + UtilDB.TABLE_DATA_TIME + "("
+ UtilDB.KEY_DATE + " TEXT PRIMARY KEY,"
+ UtilDB.KEY_TIME + " INTEGER" + ")";
db.execSQL(CREATE_DATA_TIME_TABLE); //creating our table
}
public void addWorkTime(#NotNull WorkTime workTime) {
// if there is just a date, it will update this worktime
if (thereIsADate(workTime.getDate()))
updateWorkTime(workTime);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(UtilDB.KEY_DATE, workTime.getDate());
values.put(UtilDB.KEY_TIME, workTime.getTime());
Log.d(TAG, workTime.toString());
//Insert to row
db.insert(UtilDB.TABLE_DATA_TIME, null, values); // TODO
Log.d(TAG, "addWorkTime: " + "item added");
db.close(); //closing db connection!
}
But i have this problem:
2021-05-04 21:23:02.697 16874-16874/com.application.care E/SQLiteDatabase: Error inserting date=05/04/2021 time=60000.0
android.database.sqlite.SQLiteDatatypeMismatchException: datatype mismatch (code 20)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1474)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at com.application.care.data.HandlerDB.addWorkTime(HandlerDB.java:78)
at com.application.care.ui.home.HandlerCountDownTime.setView(HandlerCountDownTime.java:61)
at com.application.care.ui.home.HomeFragment.manageCountDownTime(HomeFragment.java:27)
at com.application.care.ui.home.HomeFragment.onCreateView(HomeFragment.java:48)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2629)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2722)
at androidx.fragment.app.FragmentStateManager.activityCreated(FragmentStateManager.java:346)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1188)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
at android.app.Activity.performStart(Activity.java:6679)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2609)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 2021-05-04 21:23:02.700 16874-16874/com.application.care D/HandlerCountDownTime: []
How i can resolve?
Edit: i try do reinstall DB but there is this problem:
2021-05-05 17:54:01.039 18089-18089/com.application.care
E/SQLiteDatabase: Error inserting date=05/05/2021 time=2.6133548E7
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: DataTime.date (code 1555)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native
Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1474)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at com.application.care.data.HandlerDB.addWorkTime(HandlerDB.java:78)
at com.application.care.ui.home.HandlerCountDownTime$2.onEnd(HandlerCountDownTime.java:94)
at cn.iwgang.countdownview.CountdownView$1.onFinish(CountdownView.java:139)
at cn.iwgang.countdownview.CustomCountDownTimer$1.handleMessage(CustomCountDownTimer.java:106)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
I suspect that your issue is that you have changed the onCreate method from:-
public void onCreate(#NotNull SQLiteDatabase db) {
//SQL - Structured Query Language
String CREATE_DATA_TIME_TABLE = "CREATE TABLE " + UtilDB.TABLE_DATA_TIME + "("
+ UtilDB.KEY_DATE + " INTEGER PRIMARY KEY," //<<<<<<<<<< WAS THIS
+ UtilDB.KEY_TIME + " INTEGER" + ")";
db.execSQL(CREATE_DATA_TIME_TABLE); //creating our table
}
to
public void onCreate(#NotNull SQLiteDatabase db) {
//SQL - Structured Query Language
String CREATE_DATA_TIME_TABLE = "CREATE TABLE " + UtilDB.TABLE_DATA_TIME + "("
+ UtilDB.KEY_DATE + " TEXT PRIMARY KEY," //<<<<<<<<<< NOW THIS
+ UtilDB.KEY_TIME + " INTEGER" + ")";
db.execSQL(CREATE_DATA_TIME_TABLE); //creating our table
}
see comments indicated by //<<<<<<<<<<
But have run the first version, made the changed and then run the second version without deleting the database.
The DataType Mismatch will only happen if the an attempt is made to insert/update a row and that the rowid column or an alias of the rowid column is not an integer.
coding column_name INTEGER PRIMARY KEY is special in that it makes the column and alias of the normally hidden rowid column.
See SQLite Result and Error Codes - Result Code meanings
(20) SQLITE_MISMATCH The SQLITE_MISMATCH error code indicates a
datatype mismatch.
SQLite is normally very forgiving about mismatches between the type of
a value and the declared type of the container in which that value is
to be stored. For example, SQLite allows the application to store a
large BLOB in a column with a declared type of BOOLEAN. But in a few
cases, SQLite is strict about types. The SQLITE_MISMATCH error is
returned in those few cases when the types do not match.
The rowid of a table must be an integer. Attempt to set the rowid to
anything other than an integer (or a NULL which will be automatically
converted into the next available integer rowid) results in an
SQLITE_MISMATCH error.
Fix
The simple fix if you can afford to lose any existing data is to delete the database, this can be achieved by uninstalling the App. You can then just rerun the App.
If you have existing data that needs to be saved (probably unlikely as the data in the data column may be useless), then you need to introduce a one-off run that will:-
Create a new table with the final column definitions ensuring that the table's name is different e.g. your_table_NEW.
Populate the new table from the original table
Rename the original table using ALTER TABLE
Rename the new table to the original table name
DROP the new table.
I'm working with android studio and I need to insert some data into a database. Sometimes, it works, but sometimes, I get this error. I can't really figure out the difference between the times it works and the times it doesn't.
2019-11-09 11:38:34.912 4369-4369/com.example.android.fresh
D/DatabaseHelper: addData: Adding John Smith to people_table
2019-11-09 11:38:34.913 4369-4369/com.example.android.fresh E/SQLiteLog:
(20) statement aborts at 5: [INSERT INTO
people_table(name,amount,contact_no) VALUES (?,?,?)] datatype mismatch
2019-11-09 11:38:34.916 4369-4369/com.example.android.fresh
E/SQLiteDatabase: Error inserting name=John Smith amount=255.0 contact_no= 1234567890 from {P:4369;U:10178}
android.database.sqlite.SQLiteDatatypeMismatchException: datatype mismatch (code 20 SQLITE_MISMATCH)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1613)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1482)
at com.example.android.fresh.DatabaseHelper.addData(DatabaseHelper.java:51)
at com.example.android.fresh.createPerson.AddData(createPerson.java:94)
at com.example.android.fresh.createPerson$1.onClick(createPerson.java:58)
at android.view.View.performClick(View.java:6669)
at android.view.View.performClickInternal(View.java:6638)
at android.view.View.access$3100(View.java:789)
at android.view.View$PerformClick.run(View.java:26145)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
The relevant code in my database helper class is as follows:
private static final String COL1 = "contact_no";
private static final String COL2 = "name";
private static final String COL3 = "amount";
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COL1 + " TEXT NOT NULL," +
COL2 + " TEXT NOT NULL,"
+ COL3 + " REAL)" ;
db.execSQL(createTable);
public boolean addData(String contactNo, String contactName, double amount) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1, contactNo);
contentValues.put(COL2, contactName);
contentValues.put(COL3, amount);
Log.d(TAG, "addData: Adding " + contactName + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
This is the code in the createPerson class:
public void AddData(String contactNo, String contactName, double amount) {
boolean insertData = mDatabaseHelper.addData(contactNo, contactName, amount);
if (insertData) {
check =1;
toastMessage("Contact Inserted");
} else {
toastMessage("Something went wrong");
}
}
And this is the method call statement:
AddData(contactNumber, contactName, amount);
Each one of these is in the order contactNumber, contactName, and amount, but the sqlite error i' m getting is inserting it in the order contactName, amount, and contactNumber. I really can't understand how this is happening.
There is only 1 situation where when a data type mismatch will occur, due to SQLite being able to store any type of data in any type of column (with 1 exception and thus the cause/issue).
you wish to have a read of Datatypes In SQLite Version 3, as this explains about the type and how it is flexible in comparison to typically databases. It also explains about rowid's aliases and AUTOINCREMENT.
The exception is for a column that is an alias of the rowid column. An alias of the rowid column is defined by using INTEGER PRIMARY KEY (specifically INTEGER not INT or not any other value that will result in a derived type of INTEGER).
Note that AUTOINCREMENT is can be added to (and only to) the definition, although it is inefficient to do so, and rarely needed.
The rowid and therefore an alias thereof MUST contain an integer value (up to 64 bit signed).
As such you are somehow trying to insert a non-integer value into an alias of the rowid, this cannot be the case if the SQL as shown is used to create the table.
As such the SQL has not been successfully run and created the table, but what is very likely the cause is that a previous table exsists that was created using different SQL.
Simply changing the create SQL will not result in the table being changed. That is because a database persists (stays there) between runs. As such the onCreate method will only be automatically run once for the lifetime of the database.
If you change the schema (the create SQL), then you have to find some way of running the SQL (which would involve dropping the table). The simplest way when developing an App, is to either
delete the App's data,
to uninstall the App or to
increment the version number
this latter option will only work if the onUpgrade drops the table(s) so they can be recreated and invokes the changed SQL (typically by calling onCreate)).
After doing one of the above the App should then be rerun.
Note the above options will all result in current data being lost. If current data needs to be retained then the process is more complicated and will likely involve ALTER statements to rename tables and statements to copy (INSERT) the data from the original table(s) to the new table(s).
#MikeT already answered this correctly in detail, but nevertheless I'm wondering: why not follow architecture design patterns and implement Android Room?
Using Room, you wouldn't have to worry about this kind of "low level" error. It would tell you what is wrong and that is what it's designed for.
Tip: Let Room do the inserting for you and be happy with persistent data
I know basics about SQLite .When i was working on Reverse engineering of SQLite for android development--> Even i have copied most of the code and paste it in mine , my app show error in logcat about data mismatch.
(The error is in setNotes method down)
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context c){
super(c,"Notes_Database",null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(Note.CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Note.TABLE_NAME);
onCreate(db);
}
public long setNotes(String wordv,String reversev){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("Word",wordv);
values.put("Reverse",reversev);
//This below line where the Error occurs.
long id=db.insert(Note.TABLE_NAME,null,values);//<--
db.close();
return id;
}
My table name is :
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ "Word" + " TEXT,"
+ "Reverse" + " TEXT"+")";
And Here is My Error(That is "[INSERT INTO notes(Reverse,Word) VALUES (?,?)] datatype mismatch") :-(
> 2019-04-14 20:52:05.404 9597-9597/com.example.sqlwithjava E/SQLiteLog: (20) statement aborts at 5: ***[INSERT INTO notes(Reverse,Word) VALUES (?,?)] datatype mismatch***
2019-04-14 20:52:05.406 9597-9597/com.example.sqlwithjava E/SQLiteDatabase: Error inserting Reverse=gfdhg Word=ghdfg
android.database.sqlite.SQLiteDatatypeMismatchException: datatype mismatch (code 20)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1474)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at com.example.sqlwithjava.DatabaseHelper.setNotes(DatabaseHelper.java:47)
at com.example.sqlwithjava.MainActivity.ReverseText(MainActivity.java:30)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
And Thanks in advance.
The Issue
There is only one reason for a datatype mismatch and that is when an attempt is made to insert a non integer value into the rowid column or an alias of the rowid column. Any other column can store any type of value .
As such column Reverse or column Word has been defined as an alias of the rowid column.
An alias of the rowid is defined when you specifically code column_name INTEGER PRIMARY KEY (with or without the AUTOINCREMENT keyword) or an equivalent as per - ROWIDs and the INTEGER PRIMARY KEY.
Therefore
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ "Word" + " TEXT,"
+ "Reverse" + " TEXT"+")";
Cannot be what has been used to define the table.
A common cause of the table not being defined as expected is the frequent mis-conception that the Database Helper's onCreate method runs every time the App is run. The onCreate will only automatically be run once when the database is created. All subsequent runs will ascertain that the database exists and the onCreate method will then not run automatically.
The Fix
The fix, at least when developing the App, to apply a changed table definition is to either delete the database or to force the onCreate method to run after deleting any tables (otherwise the creation would fail, or if the table definition includes CREATE TABLE IF NOT EXISTS ........ that the attempt to create the table would be skipped).
As such the likely fix is to do one of the following :-
Delete the App's data.
Uninstall the App.
or (in your case as the onUpgrade mnethod appears to be fine (drops the table and then calls onCreate)) increase the version number (4th parameter to the SQLiteOpenHelper super call) e.g. change super(c,"Notes_Database",null,1); to super(c,"Notes_Database",null,2);
After doing one of the above, the App can then be rerun, which should introduce the changed table.
I need to reset the row number count to 1.
How can I do that?
An example for an update query in my code:
public boolean update (long rowId, String title, String body, String reminderDateTime, String loca, String type, String settime, String lat, String llong) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_BODY, body);
args.put(KEY_DATE_TIME, reminderDateTime);
args.put(KEY_LOCATION, loca);
args.put(KEY_TYPE, type);
args.put(KEY_SETTIME, settime);
args.put(KEY_LAT, lat);
args.put(KEY_LONG, llong);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
I tried to do that but the eclipse showing me an error:"sqlite_sequence cannot be resolved to a variable"
public void resetAutoNumbering ()
{
mDb.update(sqlite_sequence, args, KEY_ROWID + "=" + rowId, null);
}
What can I do and how?
Found this as answer for a similar question SQLite Reset Primary Key Field:
delete from your_table;
delete from sqlite_sequence where name='your_table';
SQLite Autoincrement
SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.
-axel
You use sqlite_sequence in your procedure but before this you used DATABASE_TABLE instead of sqlite_sequence. Change your sqlite_sequence to DATABASE_TABLE.
I have an Android SQLite Database and I inserted some rows. After I deleted these rows the ID column continues from the last ID and I would like to restart the counting from 1.
Inside your .db file there's an table called sqlite_sequence
Each row has two columns 'name' which is the name of the table 'seq' a integer indicating the current last value at this table
You can update it to 0
But beware if your table use this id as the unique identifier.
Take a look at this answer: SQLite Reset Primary Key Field
Try:
delete from sqlite_sequence where name='your_table';
If you want to reset every RowId via content provider try this
rowCounter=1;do {
rowId = cursor.getInt(0);
ContentValues values;
values = new ContentValues();
values.put(Table_Health.COLUMN_ID,
rowCounter);
updateData2DB(context, values, rowId);
rowCounter++;
while (cursor.moveToNext());
public static void updateData2DB(Context context, ContentValues values, int rowId) {
Uri uri;
uri = Uri.parseContentProvider.CONTENT_URI_HEALTH + "/" + rowId);
context.getContentResolver().update(uri, values, null, null);
}