I have an activity that runs a query on a Sqlite DB, gets a Cursor, creates a CustomCursorAdapter with that Cursor, and attaches it to the ListView in the activity. It looks like this:
SQLiteDatabase db=new StuffHelper(this).getWritableDatabase();
Cursor c1=db.query(StuffHelper.TABLE,
new String[]{StuffHelper._ID},
StuffHelper.SIZE+">=?",
new String[]{"64"},
null,
null,
null);
startManagingCursor(c1);
StuffAdapter a1 = new StuffAdapter(this, c1);
ListView ll1 = (ListView) findViewById(R.id.ll1);
ll1.setAdapter(a1);
Is this current setup a problem in terms of ANR? When using cursors, how can I tell android to run all the Sqlite stuff on a background thread?
You didn’t give much context of when this code is run, but I’ll bite anyway…
Yes, it does run the risk of an ANR. It also runs the risk of various other lifecycle problems. Since
setListAdapter()needs to be called before various other thing that you’d normally do inonCreate()you probably want to offload the database access to a separate thread (like an AsyncTask) that can be called/cached/managed as needed. AsyncTask gives you a UI-based callback before the thread starts and a UI-based callback when the thread ends. The ListAdapter can be created and assigned without any references to a Cursor (and I’d suggest you fix that asap… there doesn’t seem to be a good reason why you’re using a custom list adapter, you should be managing your database access better instead).Managing this task over activity teardown and rebuilding (think changing orientation…) is an entirely different ball of wax and has been covered ad nauseam on SO.