Using AsyncTask with database
I have the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_database);
db=new DBAdapter(this);
InitTask init_task=new InitTask();
init_task.execute(db);
}
public class InitTask extends AsyncTask <DBAdapter, Void, List<GeoPoint>> {
List<GeoPoint> geoPointsArray = new ArrayList<GeoPoint>();
DBAdapter db;
int latitude;
int longitude;
GeoPoint p;
protected List<GeoPoint> doInBackground(DBAdapter...adapters) {
try{
db.openDataBase();
Cursor c=db.getAllData();
if (c.moveToFirst()) {
do{
longitude=Integer.parseInt(c.getString(0));
latitude=Integer.parseInt(c.getString(1));
p = new GeoPoint(latitude,longitude);
geoPointsArray.add(p);
} while(c.moveToNext());
}
c.close();
db.close();
} catch(Exception e) {
Log.d("Eroare","doInBackground",e);
}
return geoPointsArray;
}
protected void onPostExecute(List<GeoPoint&开发者_如何学Gogt; geoPointsArray {
super.onPostExecute(geoPointsArray);
for (int i=0;i<geoPointsArray.size();i++) {
Log.d("Lista",geoPointsArray.get(i).toString());
}
}
}
In doInBackground
I try to read from the database and in my onPostExecute()
I try to display the data, but I get nothing, and I'm sure that I have something in the DB.
Since I do not see your declaration for AsyncTask Params,Progress,Result this is difficult to debug, but I can see two problems 1) Your doInBackground does not match the prototype doInBackground(Params...) 2) I see no code that actually does anything with geoPointsArray when the threaded doInBackground returns in onPostExecute. To answer your question, at onPostExecute you are back in the GUI thread.
I have some code here, which may or may not help.
EDIT: Consider passing db as the param
new AsynchTask<DataBase?,Void,List<GeoPoint>>
Then comment out all of the non database code. Wrap the database code in try catch Exception e. Write Log.d(TAG,"doInBackground",e) on exception. Then in onPostExecute examine the List to see what the thread in doInBackground is returning perhaps by calling Log.d(TAG,new Boolean(myList.isEmpty()).toString())
Firstly, you haven't declared your AsyncTask class correctly, as can be seen from the example in android documentation here you need to specifify the three types it will use:
public class InitTask extends AsyncTask<Params, Progress, Result>
This will fix your doInBackround problem. The reason it isn't recognised is Result needs to be substituted for your List.
To get the data back to the UI thread, you need to set up a listener, onProgressUpdate() which will get called, passing the Progress object which you send from the AsyncTask using publishProgress().
精彩评论