Reputation: 813
I have an app that propogates a spinner from a website inside an AsyncTask. Without a ProgressDialog, I am stuck with an empty spinner until it loads. With a ProgressDialog, the network operation never finishes and the ProgressDialog stays up forever. Here is my code:
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();
}
}
Upvotes: 0
Views: 1055
Reputation: 16729
Just rearrange the dismiss dialog line as follows :
protected void onPostExecute(Document doc) {
dialog.dismiss(); // rearranged
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
}
});
}
Upvotes: 1