Best Way to Refresh Adapter/ListView on Android

Simon picture Simon · Nov 16, 2010 · Viewed 155.4k times · Source

My book, "Hello Android" gives this as a way of using a custom db helper, setting up a cursor, and then setting up an adapter as follows:

Cursor cursor
CustomDatabaseHelper test = new CustomDatabaseHelper(this);
try {
        cursor = getData();
        showData(cursor);
} finally {
        test.close();
}

With this however, everytime I need to refresh the data set, I need to keep running this block of code (which gets a bit difficult inside an onClick() for a button due to "this" not being available.

Is this the best way to refresh the data set, or should I look towards removing the .close and issue an adapter.notifyDataSetChanged()? If I do this, sometimes I get a force close as (and I can't remember at the moment) but sometimes it cannot Delete properly - I think this may be because the database is currently open and it tries to open again.

Should we also be declaring the variables for the Cursors, DatabaseHelpers and Adapter in the Class (outside of the OnCreate) so that they are accessible to all the functions?

I realise this is just poor programming at this stage, but Im trying to get some pointers as to the best way of doing things.

Answer

Macarse picture Macarse · Nov 16, 2010

You should use adapter.notifyDataSetChanged(). What does the logs says when you use that?