Reputation: 6138
I have an AsyncTask posting data into a sql db, and then im fetching that data from the activity.
Problem is, because the database is empty when the app first launches it will crash trying to fetch stuff from it. So i tried to make a while() loop that will make the activity wait until the AsyncTask is done, and then fetch the data. All i get is a white screen and after a few seconds a "not responding" dialog:
MyAsyncTask task = new MyAsyncTask(this, country, img);
task.execute();
SetSql mydb = new SetSql(this);
mydb.open();
while(task.getStatus()!=AsyncTask.Status.FINISHED){
//wait
}
countryCode = mydb.getLatestCode();
Log.e("debug", countryCode);
mydb.close();
The reason im using the database anyway is because i couldn't figure out a way to send a simple string back from my AsyncTask, is there a way to do that from the postExecute?
Upvotes: 0
Views: 314
Reputation: 8781
I think you could make your own onTaskDone interface, like this:
public class TaskTest extends AsyncTask<String, Integer, String> {
interface TaskDoneListener {
abstract void onTaskDone(String result);
}
private TaskDoneListener t;
public TaskTest(TaskDoneListener t){
this.t = t;
}
@Override
protected String doInBackground(String... params) {
// do your stuf
return "some thing";
}
@Override
protected void onPostExecute(String result) {
t.onTaskDone(result);
super.onPostExecute(result);
}
}
You could use the notify and wait functions and use the onTaskDone to notify some kind of Thread that is waiting for a result.
EDIT:
execute this code in your onTaskDone method:
countryCode = mydb.getLatestCode();
Log.e("debug", countryCode);
mydb.close();
EDIT 2:
Activity example code:
public class TestActivity extends Activity implements TaskDoneListener {
/** Called when the activity is first created. */
TaskTest task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create your layout and stuff
}
@Override
protected void onStart() {
super.onStart();
//Dont start you task in the onCreate this could cause some weird behavior
//if the onCreate method is not yet done but your task is.
task = new TaskTest((TaskDoneListener) this, ##country_code?##, ##image?##);
task.execute();
}
public void onTaskDone(String result) {
//set the results in your created views
}
}
Rolf
Upvotes: 1