5

I have an app that uses many, many calls to a MySQL database; it does this inside an AsyncTask. Below is a sample of what one may look like.

My main question is this; sometimes, the host (Godaddy, ugh) decides to stall a connection and my progressDialog loads, and loads, and loads some more, until there is a force close and the app crashes. Especially if the user tries to interrupt it (most I have set to non-cancelable, however).

Is there a better way to handle this than I am below? I am doing it in a try/catch, but not sure how to use that to my advantage.

class Task extends AsyncTask<String, String, Void> {
        private ProgressDialog progressDialog = new ProgressDialog(
                MasterCat.this);
        InputStream is = null;
        String result = "";

        protected void onPreExecute() {
            progressDialog.setMessage("Loading...");
            progressDialog.show();
            progressDialog.setCancelable(false);
        }

        @Override
        protected Void doInBackground(String... params) {
            String url_select = "http://www.---.com/---/master.php";

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url_select);
            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(param));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                // read content
                is = httpEntity.getContent();

            } catch (Exception e) {

                Log.e("log_tag", "Error in http connection " + e.toString());
            }
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();

            } catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag", "Error converting result " + e.toString());
            }

            return null;

        }

        protected void onPostExecute(Void v) {

            String cat;
            try {
                jArray = new JSONArray(result);
                JSONObject json_data = null;
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);
                    cat = json_data.getString("category");

                    cats.add(cat);

                }
            } catch (JSONException e1) {
                Toast.makeText(getBaseContext(), "No Categories Found",
                        Toast.LENGTH_LONG).show();
            } catch (ParseException e1) {
                e1.printStackTrace();
            }

            ListView listView = getListView();
            listView.setTextFilterEnabled(true);

            listView.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long id) {

                    Intent i = new Intent(getApplicationContext(), Items.class);
                    i.putExtra("category", cats.get(arg2));
                    startActivity(i);

                }
            });

            progressDialog.dismiss();

            MasterCatAdapter adapter = new MasterCatAdapter(MasterCat.this,
                    cats);
            setListAdapter(adapter);

        }
    }

Edit: Now I AM assuming the force close is because of the poor connection; but I will try to get alogcat up when I can recreate it.

Edit2: here is LogCat:

08-13 14:57:00.580: E/WindowManager(2262): Activity com.---.---.MyFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@42b02cd0 that was originally added here
08-13 14:57:00.580: E/WindowManager(2262): android.view.WindowLeaked: Activity com.---.---.MyFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@42b02cd0 that was originally added here
08-13 14:57:00.580: E/WindowManager(2262):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
08-13 14:57:00.580: E/WindowManager(2262):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
08-13 14:57:00.580: E/WindowManager(2262):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
08-13 14:57:00.580: E/WindowManager(2262):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
08-13 14:57:00.580: E/WindowManager(2262):  at android.view.Window$LocalWindowManager.addView(Window.java:547)
08-13 14:57:00.580: E/WindowManager(2262):  at android.app.Dialog.show(Dialog.java:277)
08-13 14:57:00.580: E/WindowManager(2262):  at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPreExecute(MyFragmentActivity.java:374)
08-13 14:57:00.580: E/WindowManager(2262):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
08-13 14:57:00.580: E/WindowManager(2262):  at android.os.AsyncTask.execute(AsyncTask.java:534)
08-13 14:57:00.580: E/WindowManager(2262):  at com.---.---.MyFragmentActivity$RateFragment$insertTask.onPostExecute(MyFragmentActivity.java:520)
08-13 14:57:00.580: E/WindowManager(2262):  at com.---.---.MyFragmentActivity$RateFragment$insertTask.onPostExecute(MyFragmentActivity.java:1)
08-13 14:57:00.580: E/WindowManager(2262):  at android.os.AsyncTask.finish(AsyncTask.java:631)
08-13 14:57:00.580: E/WindowManager(2262):  at android.os.AsyncTask.access$600(AsyncTask.java:177)
08-13 14:57:00.580: E/WindowManager(2262):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
08-13 14:57:00.580: E/WindowManager(2262):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-13 14:57:00.580: E/WindowManager(2262):  at android.os.Looper.loop(Looper.java:137)
08-13 14:57:00.580: E/WindowManager(2262):  at android.app.ActivityThread.main(ActivityThread.java:4745)
08-13 14:57:00.580: E/WindowManager(2262):  at java.lang.reflect.Method.invokeNative(Native Method)
08-13 14:57:00.580: E/WindowManager(2262):  at java.lang.reflect.Method.invoke(Method.java:511)
08-13 14:57:00.580: E/WindowManager(2262):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-13 14:57:00.580: E/WindowManager(2262):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-13 14:57:00.580: E/WindowManager(2262):  at dalvik.system.NativeStart.main(Native Method)
08-13 14:57:00.588: D/AndroidRuntime(2262): Shutting down VM
08-13 14:57:00.588: W/dalvikvm(2262): threadid=1: thread exiting with uncaught exception (group=0x4200b300)
08-13 14:57:00.596: E/AndroidRuntime(2262): FATAL EXCEPTION: main
08-13 14:57:00.596: E/AndroidRuntime(2262): java.lang.NullPointerException
08-13 14:57:00.596: E/AndroidRuntime(2262):     at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPostExecute(MyFragmentActivity.java:461)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPostExecute(MyFragmentActivity.java:1)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at android.os.AsyncTask.finish(AsyncTask.java:631)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at android.os.Looper.loop(Looper.java:137)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at android.app.ActivityThread.main(ActivityThread.java:4745)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at java.lang.reflect.Method.invokeNative(Native Method)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at java.lang.reflect.Method.invoke(Method.java:511)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-13 14:57:00.596: E/AndroidRuntime(2262):     at dalvik.system.NativeStart.main(Native Method)

Edit: Here is the Task that is in a different activity but being referenced in LogCat:

class RatingTask extends AsyncTask<String, String, Void> {

            private ProgressDialog progressDialog = new ProgressDialog(
                    getActivity());

            InputStream is = null;
            String result = "";

            protected void onPreExecute() {
                progressDialog.setMessage("Loading...");
                progressDialog.show();
                progressDialog.setOnCancelListener(new OnCancelListener() {

                    public void onCancel(DialogInterface dialog) {
                        RatingTask.this.cancel(true);
                    }
                });
            }

            @Override
            protected Void doInBackground(String... params) {
                String url_select = "http://www.---.com/---/get_ratings.php";

                ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("item", Item));
                param.add(new BasicNameValuePair("category", Category));

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url_select);

                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(param));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();

                    // read content
                    is = httpEntity.getContent();

                } catch (Exception e) {

                    Log.e("log_tag", "Error in http connection " + e.toString());
                }
                try {
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(is));
                    StringBuilder sb = new StringBuilder();
                    String line = "";
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();

                } catch (Exception e) {
                    Log.e("log_tag", "Error converting result " + e.toString());
                }

                return null;

            }

            protected void onPostExecute(Void v) {

                String starTotal = null, starAvg = null;
                try {
                    JSONArray jArray = new JSONArray(result);
                    JSONObject json_data = null;
                    for (int i = 0; i < jArray.length(); i++) {
                        json_data = jArray.getJSONObject(i);

                        starTotal = json_data.getString("TotalRating");
                        starAvg = json_data.getString("AverageRating");

                    }
                } catch (JSONException e1) {
                    Log.e("log_tag",
                            "Error in http connection " + e1.toString());
                    Toast.makeText(getActivity(), "JSONexception",
                            Toast.LENGTH_LONG).show();
                } catch (ParseException e1) {
                    e1.printStackTrace();
                }

                int total = 0;

                if (starTotal != null) {
                    total = Integer.parseInt(starTotal);
                } else {
                    starTotal = "0";
                }

                if (total > 0) {
                    total = Integer.parseInt(starTotal);
                } else {
                    total = 0;
                }

                StarTotal = (TextView) getActivity().findViewById(
                        R.id.tvStarTotal);
                StarTotal.setText("(" + String.valueOf(total) + (")"));

                float avg = 0.f;
                try {
                    avg = Float.parseFloat(starAvg);
                } catch (NumberFormatException e) {
                    avg = 0;
                }

                DecimalFormat myFormat = new DecimalFormat("0.00");
                StarNumbers = (TextView) getActivity().findViewById(
                        R.id.tvStarNumber);
                StarNumbers.setText(myFormat.format(avg));

                ratingsBarTwo.setRating(Float.valueOf(avg));
                progressDialog.dismiss();
            }
        }
TheLettuceMaster
  • 15,594
  • 48
  • 153
  • 259
  • 2
    First of all think about http timeouts on your httpclient and catch these exceptions. In order to handle your progressdialog I'd rather display it before the task and handle it with with Handler after you got the timeout exception. Here's a good sample http://stackoverflow.com/questions/4538338/progressdialog-in-asynctask – Sergey Benner Aug 13 '12 at 21:39
  • Where would I use the AsyncTask then? Aren't they ran in parallel (Asynchronously) to whatever is happening in onCreate? (It is inside the onCreate where I call the task.) – TheLettuceMaster Aug 13 '12 at 21:42
  • Could you please post logcat's exception and check the link I've written above. – Sergey Benner Aug 13 '12 at 21:45
  • I just added a LogCat. It looks like there is much more going on than connection issues; but possibly my UI. – TheLettuceMaster Aug 13 '12 at 22:01
  • Thank you, I dont think the connection issue is the biggest problem there but overall the NULL handling + the AsyncTask flow mate. It wouldn't be a problem if you handled out those nulls. Please check the answers below. – Sergey Benner Aug 13 '12 at 22:09
  • 1
    There is definitely because of poor connections from the very beginning. Poor connection leads to no valid data and nulled variables later on. Check if your data is null before you use it, and handle poor connection (no connection) by canceling the http requests in a certain amount of time. – Wroclai Aug 13 '12 at 22:20
  • I doubt it would've been that much of a problem had he handled these nulls regardless of a root cause. It is obvious that bad data or insufficient data causes that. – Sergey Benner Aug 14 '12 at 06:51
  • You're both right. My SQL calls are all tested and valid (though definitely can be optimized for speed); and there really is no reason for me to get nulls except for the horrible connection that Godaddy provides -- and because I don't handle the nulls, the app crashes constantly. – TheLettuceMaster Aug 14 '12 at 16:56

3 Answers3

5

Begin with checking if there is a connection available, and notify the user if there isn't.

Especially if the user tries to interrupt it (most I have set to non-cancelable, however).

I would reconsider that decision. Personally, I don't like non-interruptible processes. My suggestion is that you go on from what @CommonsWare suggests in the comments here. Shortly, have a boolean variable that checks whether the data is invalid or your own check to see if your data is null. If it is, don't execute any commands based from this data and you won't have any force closes related to this.

Is there a better way to handle this than I am below?

Besides from what is stated above, I'd recommend adding some HTTP parameters to your http client. For example:

final int CONN_WAIT_TIME = 3000;
final int CONN_DATA_WAIT_TIME = 2000;

HttpParams httpParams = new BasicHttpParams();      
HttpConnectionParams.setConnectionTimeout(httpParams, CONN_WAIT_TIME);
HttpConnectionParams.setSoTimeout(httpParams, CONN_DATA_WAIT_TIME);

DefaultHttpClient postClient = new DefaultHttpClient(httpParams);

// Go on...

If your http client exceeds the time you put in their respective fields, it will simply give you a ConnectTimeoutException. Now you know enough to consider if the data is valid in onPostExecute() and whether you should go on using it or not.

Community
  • 1
  • 1
Wroclai
  • 26,835
  • 7
  • 76
  • 67
  • if I add those two parameters, what happens if they expire or timeout? basically -- nothing? in other words: no force close, just an empty list? – TheLettuceMaster Aug 13 '12 at 23:56
  • It will send you an exception, and from there you can analyze what's wrong and notifying the user. – Wroclai Aug 14 '12 at 08:23
  • I marked this correct because it's the most complete answer. So it seems best-case scenerio with a poor connection is the user may get lots of blank lists that (if data is found null) toasts "Timeout!" (or something like that). I suppose that is better than a crash. I just need to find better shared-hosting probably. – TheLettuceMaster Aug 14 '12 at 17:03
2

Your exception is caused because you still have a Dialog showing while you've entered a different Activity. Before you say

Intent i = new Intent(getApplicationContext(), Items.class);
i.putExtra("category", cats.get(arg2));
startActivity(i);

Call this:

progressDialog.dismiss()

And your activity will not leak anymore.

tolgap
  • 9,629
  • 10
  • 51
  • 65
  • That's not it. The first code snippet in this answer is inside a `setOnClickListener()` function, and it will not be called unless a user click on the view. The error is not related to this piece of code. – Wroclai Aug 13 '12 at 22:11
  • Well, the code above is actually not part of the activity that is being referenced in the LogCat. So I wouldn't look at that, sorry for not explaining that. Perhaps you can tell me what causes an activity to leak and I will check for it? – TheLettuceMaster Aug 13 '12 at 22:18
1
  1. Your doInBackground returns NULL. return null; You would usually return result; there

  2. your onPostExecute(has NuLL here) :)) as a result. and here onPostExecute(String result) and handle it out this way. Check the example posted again.

  3. You have to handle out these nulls (and perhaps dismiss this progressdialog in the
    onPostExecute() )

8-13 14:57:00.596: E/AndroidRuntime(2262):     at com.---.--  -.MyFragmentActivity$RateFragment$RatingTask.onPostExecute(MyFragmentActivity.java:461)
   08-13 14:57:00.596: E/AndroidRuntime(2262):     at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPostExecute(MyFragmentActivity.java:1)
Hardik Joshi
  • 9,477
  • 12
  • 61
  • 113
Sergey Benner
  • 4,421
  • 2
  • 22
  • 29