Hi
In my app I use a ListView to display data from the database. The data changes sometimes, for example when the user applies new filters or changes the sorting method. I use AsyncTask to get the databsase cursor that points to the new data set because sometimes data needs to be loaded from the net which can take some time.
What I do now looks something like this:
private class updateTask extends AsyncTask<Void, Void, Void> {
/*
* runs on the UI thread before doInBackground
*/
@Override
protected void onPreExecute(){
// prepare some stuff...
}
/*
* runs in a separate thread
* used for time-consuming loading operation
*/
@Override
protected Void doInBackground() {
//get new database cursor
mCursor = mDbAdapter.getCursor();
return null;
}
/*
* runs on the UI thread after doInBackground
*/
@Override
protected void onPostExecute(Void result){
if(mCursor!=null){
MyActivity.this.startManagingCursor(mCursor);
mCursorAdapter = new MyCustomCursorAdapter(MyActivity.this, mCursor);
mListView.setAdapter(mCursorAdapter);
}
}
}
This works so far but I realize that creating a new CursorAdapter and calling setAdapter on my ListView each time isn't the correct way to do it.
Also, after setAdapter the scroll position of the list is set back to the top. I found this post which describes how to do it properly. So now I want to do something like this:
onCreate(){
// ...
// create the CursorAdapter using null as the initial cursor
MyCustomCursorAdapter cursorAdapter = new MyCustomCursorAdapter(this, null);
mListView.setAdapter(cursorAdapter);
// ...
}
private class updateTask extends AsyncTask<Void, Void, Void> {
/*
* runs on the UI thread before doInBackground
*/
@Override
protected void onPreExecute(){
// prepare some stuff...
}
/*
* runs in a separate thread
* used for time-consuming loading operation
*/
@Override
protected Void doInBackground() {
//get new database cursor
mCursor = mDbAdapter.getCursor();
return null;
}
/*
* runs on the UI thread after doInBackground
*/
@Override
protected void onPostExecute(Void result){
// this returns null!
MyCustomCursorAdapter cursorAdapter = (MyCustomCursorAdapter)mListView.getAdapter();
Cursor oldCursor = cursorAdapter.getCursor();
if(oldCursor!=null){
MyActivity.this.stopManagingCursor(oldCursor);
oldCursor.close();
}
if(mCursor!=null){
MyActivity.this.startManagingCursor(mCursor);
cursorAdapter.changeCursor(mCursor);
}
}
}
This however doesn't work for me because
(MyCustomCursorAdapter)mListView.getAdapter();
always returns null.
Why does this happen? What am I doing wrong?
Edit:
Some additional information: my adapter implements SectionIndexer. I don't really think that this has anything to do with my problem but it has caused me some troubles before so I thought I'd mention it.