Avoiding ANRs with Cursors
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 in onCreate()
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.
Please separate your UI from background tasks. Write the cursor portion in background and in forground you can show any UI or progress dialog. Use AsyncTask for this
AsyncTask class has following methods
1. doInBackground: Code performing long running operation goes in this method. When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed.
2. onPostExecute: This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
3. onPreExecute: This method is called before doInBackground method is called.
4. onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method.
How to use AsyncTask
Thanks Deepak
精彩评论