我在我的RetrieveHttp
中放了一个名为AsycTask
的子类MainActivity
,它应该在后台执行一些处理。
活动应如下工作: 显示UI,启动后台任务(检索URL,解析内容到String数组)以及AsyncTask完成后,应该在UI上创建Toast。
不幸的是,UI正在等待doInBackground()
方法完成的任务。只有当AsyncTask
完成时,才会显示用户界面,同时用户只会看到黑屏。你能给我一些建议吗,我的代码出了什么问题?
public class Splashscreen extends Activity implements OnClickListener {
private String questions[];
//HTTP-Downloader to InputStream
private RetrieveHttp myHttp = new RetrieveHttp();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hauptmenue);
//..implementing some listeners here, referencing GUI elements
try {
questions = myHttp.execute("http://myurl.de").get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.hauptmenue, menu);
return true;
}
public void onClick(View v) {
//doing some stuff...
}
public class RetrieveHttp extends AsyncTask<String, Void, String[]> {
protected void onPreExecute() {
}
@Override
protected String[] doInBackground(String... params) {
URL url;
String string = "";
String[] questions = null;
InputStream content = null;
try {
url = new URL(params[0]);
content = getInputStreamFromUrl(url.toString());
try {
// Stream to String
string = CharStreams.toString(new InputStreamReader(
content, "UTF-8"));
questions = string.split("#");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return questions;
}
protected void onPostExecute(String[] string) {
Toast.makeText(getApplicationContext(),
"Finished", Toast.LENGTH_LONG).show();
return;
}
}
public static InputStream getInputStreamFromUrl(String url) {
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.e("[GET REQUEST]", "Network exception", e);
}
return content;
}
}
答案 0 :(得分:5)
因为这行
questions = myHttp.execute("http://myurl.de").get();
get
方法等待asynctask完成,基本上否定了异步任务的假设。
删除get并在asynctask的questions
中设置onPostExecute
,UI将显示为正常