Tuesday, July 12, 2011

Loading a ListView from a SQLite Database


Users can add Connexions content they like to a list of Favorites. The Favorites are saved in a SQLite database on the phone. These Favorites are not to be confused with the Favorites that are part of the Connexions web site. On cnx.org, the user has to log in to add content to their favorites. In the Android app, no login is required because the favorites are stored on the phone.

In ViewFavsActivity, readDB() displays a ProgressDialog and calls a ContentProvider to read the contents of the favs table. DBUtils.readCursorIntoList() takes the Cursor object returned by the ContentProvider and reads the query results into a List of Content objects. This list is then sorted and added to the ListAdapter where it is displayed.


private void readDB()
{
progressDialog = ProgressDialog.show(
ViewFavsActivity.this,
getResources().getString(R.string.loading_favs_title),
getResources().getString(R.string.loading_favs_description)
);
Thread loadFavsThread = new Thread()
{
public void run()
{

content = DBUtils.readCursorIntoList(getContentResolver().query(Favs.CONTENT_URI, null, null, null, null));

Collections.sort((List)content);

fillData(content);
handler.post(finishedLoadingListTask);
}
};
loadFavsThread.start();

}


The ContentProvider used is the ConnexionsProvider class. All of the work is done in a separate Thread which is the proper handling of any task in Android. The ProgressDialog does not display for very long unless the user has saved a long list of Favorites.

You can browse the source or download a zip file of the source. Connexions for Android is available in the Android Market or from the Connexions website.