Error in doBackground AsyncTask?
I keep getting a error in my doInBackground()
07-20 21:05:20.859: ERROR/AndroidRuntime(3289): java.lang.RuntimeException: An error occured while executing doInBackground()
07-20 21:05:20.859: ERROR/AndroidRuntime(3289): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Here is my asyncTask method.
private class MyTask extends AsyncTask<Void, Void,开发者_运维技巧 Void>{
@Override
protected Void doInBackground(Void... arg0) {try {
getImages();
Log.v("MyTask", "Image 1 retreived");
getImage2();
Log.v("MyTask", "Image 2 retreived");
getImage3();
Log.v("MyTask", "Image 3 retreived");
getImage4();
Log.v("MyTask", "Image 4 retreived");
} catch (IOException e) {
Log.e("MainMenu retreive image", "Image Retreival failed");
e.printStackTrace();
}
return null;
}
protected Void onPostExecute(){
((Gallery) findViewById(R.id.gallery))
.setAdapter(new ImageAdapter(MainMenu.this));
return null;
}
}
}
And its still holding up my UI for some reason. the UI doesnt appear till after its done.
Here is my onCreate() where i execute the AsyncTask.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyTask myTask = new MyTask();
myTask.execute();
}
You cannot manipulate the UI while you are not in the UI thread.
AsyncTask documentation
I am going to go out on a limb and guess that your time consuming call is getImages()
. If this is the case, these method calls should happen in the doInBackground()
method, and the code you currently have in the doInBackground()
method should probably be moved to the onPostExecute()
method.
Yoshi you'll actually want to move everything in your AsynkTask around. Put the load images functions into the do in background method and then on the setListAdapter call into the onPostExecute method the Doinbackground method can not change or update a view however the onPostexecute should be able to.
protected void onPostExecute(Exception error) {
try {
if (error == null) {
((Gallery) findViewById(R.id.gallery))
.setAdapter(new ImageAdapter(MainMenu.this));
} else
throw error;
} catch (Throwable t) {
}
}
精彩评论