0

My app keeps crashing and when I look at my logcat I get two sets of errors and my app crashes. I would really be thankful if somebody could tell me what's wrong and what could I do to prevent it.

07-27 11:05:53.647: E/AndroidRuntime(913): FATAL EXCEPTION: AsyncTask #2
07-27 10:36:54.139: E/AndroidRuntime(775): java.lang.RuntimeException: An error occured while executing doInBackground()
07-27 10:36:54.139: E/AndroidRuntime(775):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-27 10:36:54.139: E/AndroidRuntime(775):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-27 10:36:54.139: E/AndroidRuntime(775):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-27 10:36:54.139: E/AndroidRuntime(775):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-27 10:36:54.139: E/AndroidRuntime(775):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-27 10:36:54.139: E/AndroidRuntime(775):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-27 10:36:54.139: E/AndroidRuntime(775):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-27 10:36:54.139: E/AndroidRuntime(775):  at java.lang.Thread.run(Thread.java:856)
07-27 10:36:54.139: E/AndroidRuntime(775): Caused by: java.lang.NullPointerException
07-27 10:36:54.139: E/AndroidRuntime(775):  at com.theproblemsolver.ListView$LoadAllData.doInBackground(ListView.java:92)
07-27 10:36:54.139: E/AndroidRuntime(775):  at com.theproblemsolver.ListView$LoadAllData.doInBackground(ListView.java:1)
07-27 10:36:54.139: E/AndroidRuntime(775):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-27 10:36:54.139: E/AndroidRuntime(775):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-27 10:36:54.139: E/AndroidRuntime(775):  ... 4 more 

This is the other error my logcat is giving me...

theproblemsolver.ListView has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d0e800 V.E..... R.....ID 0,0-234,72} that was originally added here
07-27 11:05:56.119: E/WindowManager(913): android.view.WindowLeaked: Activity com.theproblemsolver.ListView has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d0e800 V.E..... R.....ID 0,0-234,72} that was originally added here
07-27 11:05:56.119: E/WindowManager(913):   at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
07-27 11:05:56.119: E/WindowManager(913):   at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
07-27 11:05:56.119: E/WindowManager(913):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
07-27 11:05:56.119: E/WindowManager(913):   at android.app.Dialog.show(Dialog.java:281)
07-27 11:05:56.119: E/WindowManager(913):   at com.theproblemsolver.ListView$LoadAllData.onPreExecute(ListView.java:85)
07-27 11:05:56.119: E/WindowManager(913):   at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
07-27 11:05:56.119: E/WindowManager(913):   at android.os.AsyncTask.execute(AsyncTask.java:534)
07-27 11:05:56.119: E/WindowManager(913):   at com.theproblemsolver.ListView.onCreate(ListView.java:52)
07-27 11:05:56.119: E/WindowManager(913):   at android.app.Activity.performCreate(Activity.java:5104)
07-27 11:05:56.119: E/WindowManager(913):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
27 11:05:56.119: E/WindowManager(913):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-27 11:05:56.119: E/WindowManager(913):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-27 11:05:56.119: E/WindowManager(913):   at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-27 11:05:56.119: E/WindowManager(913):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-27 11:05:56.119: E/WindowManager(913):   at android.os.Handler.dispatchMessage(Handler.java:99)
07-27 11:05:56.119: E/WindowManager(913):   at android.os.Looper.loop(Looper.java:137)
07-27 11:05:56.119: E/WindowManager(913):   at android.app.ActivityThread.main(ActivityThread.java:5041)
07-27 11:05:56.119: E/WindowManager(913):   at java.lang.reflect.Method.invokeNative(Native Method)
07-27 11:05:56.119: E/WindowManager(913):   at java.lang.reflect.Method.invoke(Method.java:511)
07-27 11:05:56.119: E/WindowManager(913):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-27 11:05:56.119: E/WindowManager(913):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-27 11:05:56.119: E/WindowManager(913):   at dalvik.system.NativeStart.main(Native Method

MainActivity

public class MainActivity extends Activity {

    EditText et;
    Button getanswer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button getanswer = (Button) findViewById(R.id.button1);
        getanswer.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, ListView.class);
            startActivity(i);
        }


        });
    } 
}

ListView Activity

public class ListView extends ListActivity {

    private ProgressDialog pDialog;

    JSONParsser jParser = new JSONParsser();
    ArrayList<HashMap<String, String>> questionList;

    private static String URI = "http://example.com/json";;

    //JSONObject json = jParser.getJSONFromURI(URI); 

     final String TAG_RESULTS = "ResultsSet";
     final String TAG_SUBJECT = "Subject";
     final String TAG_NUMANSWERS = "NumAnswers";
     final String TAG_QUESTION = "Question";
     final String TAG_QUESTION_CONTENT = "Content";
     final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer";
     final String TAG_QUESTION_ANSWERS = "Answers";

            JSONArray ResultsSet = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        //setContentView(R.layout.listview);

    questionList = new ArrayList<HashMap<String, String>>();

    android.widget.ListView lv = getListView(); 

    new LoadAllData().execute();

    lv.setOnItemClickListener(new OnItemClickListener() {

    @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {


        }
    });

}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 100) {
            Intent intent = getIntent();
            startActivity(intent);
            finish();
        }
    }

    class LoadAllData extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ListView.this);
            pDialog.setMessage("Loading Data. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args) {

            try {
                    JSONObject json = jParser.getJSONFromURI(URI);
                    ResultsSet = json.getJSONArray(TAG_RESULTS);

                   for(int i = 0; i < ResultsSet.length(); i++) {
                       JSONObject r = ResultsSet.getJSONObject(i);
                       String Subject = r.getString(TAG_SUBJECT);
                       String NumAnswers = r.getString(TAG_NUMANSWERS);

                       JSONObject Question = r.getJSONObject(TAG_QUESTION);
                       String Content = Question.getString(TAG_QUESTION_CONTENT);
                       String ChosenAnswer = Question.getString(TAG_QUESTION_CHOSENANSWER);
                       String Answers = Question.getString(TAG_QUESTION_ANSWERS);

                       HashMap<String, String> map = new HashMap<String, String>();

                       map.put(TAG_SUBJECT, Subject);
                       map.put(TAG_NUMANSWERS, NumAnswers);

                       questionList.add(map);
                   }



            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;


        }


        protected void onPostExecute(String file_URI) {

            pDialog.dismiss();
            runOnUiThread(new Runnable() {
            public void run() {
                ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
                        R.layout.row,
                        new String[] { TAG_SUBJECT, TAG_NUMANSWERS }, new int[] {
                        R.id.Subject, R.id.NumAnswers });

                setListAdapter(adapter);



                }
            });

        }
}}

This my JSONParsser class that contains the JSONObject json = jParser.getJSONFromURI(URI); method

public class JSONParsser {


    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    EditText et;

    public JSONParsser () {
    }

    public JSONObject getJSONFromURI(String URI) {

        try{
        HttpClient client = new DefaultHttpClient();
        try {
            URI website = new URI("http://example.com/json");
            HttpGet request = new HttpGet();
            request.setURI(website);
            try {
                HttpResponse response = client.execute(request);
            HttpEntity httpEntity = response.getEntity();
            is = httpEntity.getContent();

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        return jObj;

        }finally{}

    }{

    }

}
  • Hi! Your NPE is happening on line 92 in your ListView class. I'm not gonna help you with that because it's probably some json-parsing thing, please use the debugger to find out which values the local variables has! But another error you have is much more critical, in your HTTP method, please do this: response.getEntity().consumeContent(). Otherwise you will have your heap full with apache crap. Or if your using apache httpclient >= 4.0 something, do EntityUtils.consume(entity). Also, please close your is stream with is.close(). Also, avoid globals please. Use local variables! – Johan S Jul 28 '13 at 13:00
  • I get an error under `response.getEntity().consumeContent().` that says "Type mismatch: cannot convert from void to HtttpEntity" – Tommy Kind Jul 28 '13 at 14:15
  • `Did you try EntityUtils.consume(response.getEntity())`;? Check this question: http://stackoverflow.com/questions/4775618/httpclient-4-0-1-how-to-release-connection – Johan S Jul 28 '13 at 16:03
  • I get an error under `consume` that says "The method consume(HttpEntity) is underfined for the type EntityUtils" – Tommy Kind Jul 28 '13 at 18:21
  • eah, it's because your apache version is below 4.0.x something, please try this: `response.getEntity().consumeContent();`, it should work! And you have to catch an `IOException` when you do this. Here is the link to the HttpEntity docs for Android: http://developer.android.com/reference/org/apache/http/HttpEntity.html#consumeContent() – Johan S Jul 28 '13 at 19:30

1 Answers1

0

Okay I'll write an answer instead:

To start with you assign the content to the InputStream and then you return the JSONObject which you haven't even assigned, so therefore you get a NullPointerException. You have to parse the content of the inputstream. I would do something like this instead:

HttpEntity httpEntity = response.getHttpEntity();
String resultString = EntityUtils.toString(httpEntity);

httpEntity.consumeContent();

return new JSONObject(resultString);

NOTE: The code above doesn't catch any exceptions, you will have to fix that.

Then you have alot of globals which are unnecessary, none of your globals are needed. Convert them to locals. Also please nullcheck the response, and read the statusCode of the response so it is a 200 before returning the JSONObject.

Also: The onPostExecute always runs on the UI thread, only doInBackground is on another thread.

The window leak is because you don't Override a onDestroy() and close your AsyncTask. Do something like this (when you start the AsyncTask keep a reference to it):

@Override
public void onDestroy() {
    super.onDestroy();

    if (myAsyncTask != null) {
        myAsyncTask.cancel(true);
        myAsyncTask = null;
    }
}
Johan S
  • 3,531
  • 6
  • 35
  • 63