Wednesday, November 14, 2012

Android sqlite database questions

Android apps can easily use sqlite databases for data storage. Here are a few questions and answers about sqlite databases on android accessed via the SQLiteOpenHelper class.

1. What happens to the database associated with a given app, when the app is uninstalled?
If you create the table using internal storage, the database is wiped out. 
If you created the table on external storage, the data is preserved.  
- Another way to clear out a database is to go to Settings --> Apps --> Go to an App, and then click "Clear data".

2. How do you make changes to a database, like adding columns or an index?
In your class you should declare a variable for the version number like:
private static final int DATABASE_VERSION = 1;
When you want to make an update, change the database version to 2.
You will also need to override the onUpgrade function like this:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
{
// Depending on whether an old version existed
// and what version you are going to,
// you can customize what tables should be
// added, deleted or modified.
if ( oldVersion == 1 && newVersion == 2 )
{
// Do something.
}

// Call your onCreate function if you want ...
onCreate(db);
}
While this may seem obvious, I don't think you can 'downgrade' your database version number. At least for me this caused my app to crash.

Also, if you call another function from onUpgrade or onCreate, make sure to pass the 'SQLiteDatabase db' argument to that function as well.  Creating another db reference will cause errors.

More questions to come if I ever learn anything else ...

No comments:

Post a Comment