Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask onPreExecute progressdialog

I have an AsyncTask when onPreExecute function executes it gives me an exception

** java.lang.IllegalStateException: View com.android.internal.policy.impl.PhoneWindow$DecorView@44ea0e20 has already been added to the window manager.**

when progressDialog's show() method is called.

My Activity

public class TopNewsActivity extends ListActivity {

public static final String LOG_TAG = "Infra";
private ProgressDialog progressDialog;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listplaceholder);
    new BackgroundAsyncTask().execute();
}

public class BackgroundAsyncTask extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(TopNewsActivity.this);
        progressDialog.setCancelable(true);
        progressDialog.setMessage("Loading...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setProgress(0);
        progressDialog.show();
    }

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(String... paths) {
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        String xml = XMLfunctions.getTopNewsXML();
        Document doc = XMLfunctions.XMLfromString(xml);

        int numResults = XMLfunctions.numResults(doc);
        Log.d(LOG_TAG, "Number of Results: " + numResults);
        if ((numResults <= 0)) {
            Toast.makeText(TopNewsActivity.this, "No Result Found",Toast.LENGTH_LONG).show();
            finish();
        }

        NodeList nodes = doc.getElementsByTagName("result");

        for (int i = 0; i < nodes.getLength(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();

            Element e = (Element) nodes.item(i);
            map.put("id", XMLfunctions.getValue(e, "id"));
            map.put("title", XMLfunctions.getValue(e, "title"));
            mylist.add(map);
        }
        return mylist;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
        ListAdapter adapter = new SimpleAdapter(TopNewsActivity.this, result, R.layout.list_item, new String[] { "title" }, new int[] { R.id.item_title });
        setListAdapter(adapter);
        progressDialog.dismiss();

        final ListView lv = getListView();

        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() {
            @SuppressWarnings("unchecked")
            @Override
            public void onItemClick(AdapterView<?> a, View view, final int position, long id) {

                    HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);

                    Intent i = new Intent(TopNewsActivity.this, NewsDetails.class);
                    i.putExtra("content_id", o.get("id"));
                    i.putExtra("title", o.get("title"));
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    View v = TopNewsGroup.group.getLocalActivityManager().startActivity("ShowNews", i).getDecorView();

                    // Again, replace the view
                    TopNewsGroup.group.setContentView(v);

            }
        });

    }

}

public class MySimpleAdapter extends SimpleAdapter {
     public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
        super(context, data, resource, from, to);
        // TODO Auto-generated constructor stub
}

}
}

Please Help!!!!!

like image 589
ReNa Avatar asked Apr 29 '11 13:04

ReNa


People also ask

Why did AsyncTask get deprecated?

Official Reason for Deprecation of AsyncTask AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.

What is the replacement of AsyncTask?

AsyncTask is used to perform time talking operations in android, but it's marked as deprecated from android 11. There are many alternatives are available for replacing an AsyncTask, one of the replacements is ExecutorService.

What are the steps of AsyncTask?

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

What are the three generic types of an AsyncTask?

It's so frequent that Android provides ready to use API for such kinds of scenarios. AsyncTask is basically an API. AsyncTask is defined by three generic types. These are called Params, Progress, and Result.


4 Answers

There is a usual problem with progressdialogs and contexts, it happens to me all the time and there's a section on the android doc for this exact problem. You have probably declared it with a context of "this" when the context should actually be the name of your Java class followed by ".this".

dialog = ProgressDialog.show(Example.this, "",
                "Doing stuff. Please wait...", true);

This is because you want the progressDialog to show in the main class, not in the Async class.

If this doesn't solve it, you'll need to post the code.

like image 164
NotACleverMan Avatar answered Sep 27 '22 18:09

NotACleverMan


if ((numResults <= 0)) {
    Toast.makeText(TopNewsActivity.this, "No Result Found.",Toast.LENGTH_LONG).show();
    finish();
}

I believe this is not a good thing to do. Don't finish your activity from the non ui thread. Just return null.

like image 37
Vladimir Ivanov Avatar answered Sep 27 '22 17:09

Vladimir Ivanov


Try removing the super.onPreExecute();

like image 38
CaseyB Avatar answered Sep 27 '22 16:09

CaseyB


Thank you everybody but i've figured out what the problem was, I'm using ActivityGroup so I needed to put progressDialog = new ProgressDialog(TopNewsGroup.group); this solved my problem

:)

like image 23
ReNa Avatar answered Sep 27 '22 18:09

ReNa