I am building a very simple app that contains a SQLiteDatabase
which I want to display in a ListFragment
, using a custom SimpleCursorAdapter
.
My code is working fine, but I'm not sure if I'm doing things the correct way. I have searched a lot for (authoritative) examples of this, but have only found either overly simplified examples using ArrayAdapter
, or overly complicated examples using ContentProvider
.
ListFragment
public class CallListFragment extends ListFragment{
private CallListDbHelper dbHelper;
private SQLiteDatabase db;
private Cursor cursor;
private CallListAdapter adapter;
@Override
public void onResume() {
super.onResume();
// Create a database helper
dbHelper = new CallListDbHelper(getActivity());
// Get the database
db = dbHelper.getReadableDatabase();
// Get a cursor to the entire call list from the database
cursor = db.query( // SELECT
CallEntry.TABLE_NAME, // FROM ...
new String[] { // <columns>
CallEntry._ID,
CallEntry.COLUMN_NUMBER,
CallEntry.COLUMN_TIME },
null, // WHERE ... (x = ?, y = ?)
null, // <columnX, columnY>
null, // GROUP BY ...
null, // HAVING ...
CallEntry.COLUMN_TIME + " DESC" // ORDER BY ...
);
adapter = new CallListAdapter(getActivity(), cursor);
setListAdapter(adapter);
}
@Override
public void onPause() {
super.onPause();
// Close cursor, database and helper
if( null !=cursor ) cursor.close();
if( null != db ) db.close();
if( null != dbHelper ) dbHelper.close();
}
}
Adapter
public class CallListAdapter extends SimpleCursorAdapter {
private static final String[] FROM = {
CallListContract.CallEntry.COLUMN_NUMBER,
CallListContract.CallEntry.COLUMN_TIME
};
private static final int[] TO = {
R.id.phoneNumber,
R.id.time
};
public CallListAdapter(Context context, Cursor cursor){
this(context, R.layout.listitem_call, cursor, FROM, TO);
}
private CallListAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to) {
super(context, layout, cursor, from, to, 0);
}
}