Someone Somewhere
Someone Somewhere

Reputation: 23787

Data not written to sqlite db if power is lost shortly after write

My app inserts some data into its SQLite DB and the app confirms that the insert was successful. However, if power is lost shortly afterward, the data is not visible after the mobile device fully reboots.

It seems that there is some caching going on - how can I 'flush' the buffer / cache ?

Note: the sqlite db is located on the main flash memory, not on the sdcard.

Upvotes: 1

Views: 883

Answers (1)

Dave
Dave

Reputation: 3218

Hi Someone Somewhere,

If you want to guarantee that a DB write occurs, you should use transactions.

ie: Here is a simple example which you could build off of.

DatabaseHelper readDB = new DatabaseHelper(Context);
SQLiteDatabase db = readDB.getWritableDatabase();

String lastConnID = "1";
String DATABASE_TABLE = "TestDB";
String KEY_ROWID = "pkey";

db.beginTransaction();
db.update(DATABASE_TABLE, values, KEY_ROWID + "="
                    + "'" + lastConnID + "'", null);
db.setTransactionSuccessful();
db.endTransaction();

A sample DatabaseHelperClass can be found here.

When you call setTransactionSuccessful, the deed is done and the item should be committed to the DB. You should end the transaction right after this is called because it will still commit to the database even if an error occurs between setting the transaction successful and ending the transaction.

Hopefully this helps you! Cheers.

Upvotes: 1

Related Questions