我的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.
这是我的asyncTask方法。
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;
}
}
}
由于某种原因,它仍然保持着我的用户界面。用户界面完成后才会出现。
这是我的onCreate(),其中我执行AsyncTask。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyTask myTask = new MyTask();
myTask.execute();
}
答案 0 :(得分:1)
当您不在UI线程中时,无法操纵UI。
我想出局,并猜测你耗时的电话是getImages()
。如果是这种情况,这些方法调用应该在doInBackground()
方法中进行,并且您doInBackground()
方法中当前拥有的代码可能应该移至onPostExecute()
方法。
答案 1 :(得分:0)
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) {
}
}