package com.commonsware.cwac.wakeful.demo;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.widget.SimpleCursorAdapter;
public class FlightListActivity extends ListActivity {
private SQLiteDatabase database;
private String fields[] = {BaseColumns._ID, "name", "flights", "distance"};
private SimpleCursorAdapter dataSource;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(ACTIVITY_SERVICE, "onCreate flights");
database = (SQLiteDatabase) getLastNonConfigurationInstance();
if (database == null) {
database = getData();
Log.v(ACTIVITY_SERVICE, "first load data");
}
Cursor data = database.query("pilots", fields, null, null, null, null, null);
dataSource = new CustomCursorAdapter(this, R.layout.row, data, fields, new int[] { R.id.id, R.id.name, R.id.flights, R.id.distance });
setListAdapter(dataSource);
}
protected SQLiteDatabase getData() {
DataBaseHelper myDbHelper = new DataBaseHelper(this.getApplicationContext());
return myDbHelper.openDataBase();
}
@Override
public Object onRetainNonConfigurationInstance() {
Log.v(ACTIVITY_SERVICE, "reusing data");
final SQLiteDatabase myData = database;
return myData;
}
@Override
protected void onDestroy() {
database.close();
super.onDestroy();
}
}
Ok so I am trying to hold on to my database by storing it in the onRetainNonConfigurationInstance, but I get a runtime error if I do not close the database in the onDestroy method.
What I don’t get it, if I close the database in onDestroy, then I need to reopen it again somewhere, but doesn’t that defeat the object of holding on to it in the first place?
Is this the best way to reuse the database when user rotates the device?
In general, don’t worry about this stuff – Android as actually very efficient when it comes to doing this sort of thing. Everything has to be recreated from scratch so in most cases, just let it happen.
Opening the DB has a minimal cost in comparison to a query on it which might return a huge number of results. In saying that, that’s the point of a
Cursorin that it is designed to handle the results from a query in an efficient manner.As for
ListViewsthey only ever have a finite number of ‘items’ at any one time which are recycled as theListViewis scrolled and during an orientation change, theListViewwill need to be re-drawn usually with a different number of visible list items.The use of
onRetainNonConfigurationInstance()is a special case designed for more complex scenarioss – perhaps retain a canvas the user is drawing on, or ‘live’ network connections which are maintaining some sort of session state (authentication tokens etc).