An example analysis of Sqliteopenhelper developed by Android

  • 2020-06-19 11:43:21
  • OfStack

An example of Sqliteopenhelper is presented in this paper. Share to everybody for everybody reference. The specific analysis is as follows:

If you use openOrCreateDatabase(name, mode, factory) in Activity directly in Android development, you will have a series 1 following problem. Such as database upgrade, update, etc.

It is best to use the encapsulated version: SQLiteOpenHelper

The main job of inheriting and extending the SQLiteOpenHelper class is to override the following two methods.

onCreate(SQLiteDatabase db) : This method is executed when the database is first created. In general, initialization operations such as creating tables are performed in this method.

onUpgrade(SQLiteDatabse dv, int oldVersion,int new Version) : This method is called when the version number passed in is different from the current version number when the database is opened.

In addition to the two methods you must implement above, you can optionally implement the onOpen method, which is invoked every time the database is opened.

Rewrite these functions yourself in the business, and then use getWritableDatabase and getReadableDatabase of helper to get the database you want to manipulate. Just do it again.

In addition, the following method can be used to determine whether a table exists in sqlite:


String sql = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='items'"; 
Cursor cur = db.rawQuery(sql, null); 
int count = -1; 
while (cur.moveToNext()) { 
  count = cur.getInt(0); 
} 
if (count <= 0) { 
  //  Table does not exist  
} else {

}

I hope this article has been helpful for your Android programming.


Related articles: