【发布时间】:2014-04-29 17:50:23
【问题描述】:
我在我的MainActivity 中放置了一个名为RetrieveHttp 的子类扩展AsycTask,它应该在后台进行一些处理。
活动应按以下方式工作: 显示 UI,启动后台任务(检索 URL,将内容解析为字符串数组),当 AsyncTask 完成后,它应该在 UI 上创建一个 Toast。
不幸的是,UI 正在等待 doInBackground() 方法完成的任务。只有当AsyncTask 完成时,UI 才会显示,同时用户只会看到黑屏。请您给我一些建议,我的代码有什么问题?
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;
}
}
【问题讨论】: