I've got this inner class as part of an application which doesn't accept changes in orientation (it makes more sense in landscape orientation).
private class initialDBQuery extends AsyncTask<SQLiteDatabase, Void, Cursor> {
@Override
protected Cursor doInBackground(SQLiteDatabase... params) {
final SQLiteDatabase mDatabase = params[0];
mCursor = mDatabase.rawQuery("SELECT * FROM database", null);
return mCursor;
}
@Override
protected void onPostExecute(Cursor c){
ParentActivity.this.mCursor = mCursor;
ParentActivity.this.updateQuery();
mDatabase.close(); //Close database connection AS开发者_如何学PythonAP
}
// can use UI thread here
protected void onPreExecute() {
ParentActivity.this.mAnimalPager = null;
Toast.makeText(ParentActivity.this.getBaseContext(), "Loading Database...", Toast.LENGTH_SHORT).show();
}
}
My main UI has a number of buttons which lead to different activities, the function of which is to provide search criteria via intents to the main activity (ParentActivity) which will then perform a search. the rest of the main activity is a viewpager which dependsonthe cursor returned from the AsyncTask (the update of this is working fine).
My problem is that: with this code i, I press one of the onscreen buttons (launch another activity) while the asynctask is running then I get the error "Unable to pause activity".
what are the further steps I need to take to deal with the running of the AsyncTask when the app pauses?
thanks, m
The problem I was experiencing here was actually to do with the viewpager I have on the main activity.
As the AsyncTask was creating a cursor for the PagerAdapter i wasn't setting the adapter until it had finished. There is a known problem with ViewPagers and activity onPause when an adapter has not been set (see here).
To overcome this I modified my adapter to return 0 when there is no cursor available to the adapter:
public int getCount() {
// return the size of the cursor if it has been instantiated;
return (mCursor !=null) ? mCursor.getCount() : 0 ;
}
and added a setCurrentCursor method to the adapter. This way I was able to set the adapter up and bind it to the viewpager in onCreate and then add the cursor to the adapter when it became available from the ASyncTask;
public void setCurrentCursor(Cursor cu){
this.mCursor = cu;
this.notifyDataSetChanged();
}
Now all I have to do is call adapter.setCurrentCursor in the onPostExecute method of the ASyncTask passing in the created cursor.
Hope this helps.
Thanks, m
first try to cancel the asynctask and then start another activity may be that work for you.
精彩评论