【发布时间】:2013-08-12 19:46:13
【问题描述】:
我有一个应用程序可以从 AsyncTask 中的网站传播微调器。如果没有 ProgressDialog,我会被一个空的微调器卡住,直到它加载。使用 ProgressDialog,网络操作永远不会完成,ProgressDialog 会永远保持不变。这是我的代码:
class TheaterGetter extends AsyncTask<Void, Void, Document> {
private Context context;
private ProgressDialog dialog;
public TheaterGetter(Context context) {
this.context = context;
dialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute() {
dialog.setMessage(((Activity) context).getString(R.string.loading_theaters));
dialog.setCancelable(false);
dialog.show();
}
protected Document doInBackground(Void...voids) {
Document doc = null;
try {
doc = Jsoup.connect("http://landmarkcinemas.com").timeout(10000).get();
} catch (IOException e) {
Log.e("landmark cinemas connection error", e.getMessage());
}
return doc;
}
protected void onPostExecute(Document doc) {
Element allOptions = doc.select("select[id=campaign").first();
Elements options = allOptions.getElementsByTag("option");
options.remove(0);
TreeMap<String, String> theaters = new TreeMap<String, String>();
for (Element option:options) {
theaters.put(option.html(), option.attr("value"));
}
final TreeMapSpinAdapter adapter = new TreeMapSpinAdapter(context, android.R.layout.simple_spinner_item, theaters);
final Spinner spinner = (Spinner) ((Activity) context).findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
MainActivity.setTheater((String) adapter.getItem(pos));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
dialog.dismiss();
}
}
【问题讨论】:
-
我认为这与您的问题无关,但您应该解析
doInBackground中的文档,并返回结果theaters,以便onPostExecute可以在UI 上显示它们。解析可能需要一些时间才能运行,因此您应该避免在 UI 线程上进行。 -
哦。出于某种原因,我认为谨慎使用 doInBackground 会很好,但我明白你的意思。
标签: android android-asynctask progressdialog