2

I am working on android application and I need to parse my json object with data. How you can see I create JSONParser class and try to use asynctask but there is something wrong and I can't understand where is the problem. Every time I use it resultJSON is null. Hope that you can give me an advice!

public class JSONParser {
    private String resultJSON;

public JSONArray getJSON(String url) throws JSONException {
    Parser parser = new Parser();
    parser.execute(url);
    return json;
}

private class Parser extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        for (String url : urls) {
            StringBuilder builder = new StringBuilder();
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
                HttpResponse response = client.execute(httpGet);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(content));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                    resultJSON = builder.toString();
                } else {
                    Log.e(JSONParser.class.toString(), "Failed to download file");
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
      }
      return resultJSON;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            json = new JSONArray(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
}
user1107922
  • 610
  • 1
  • 12
  • 25
  • What does your log say? It should have either a stack trace or "Failed to download file" since `.toString()` shouldn't ever be null from a `StringBuilder`. – Cat Dec 28 '12 at 19:44
  • ur getting this error as your JSONArray doesn't wait for async task to finish . – Code_Life Dec 28 '12 at 19:58
  • Add `onPostExecute` method to your async task and move the `JSONArray json = new JSONArray(resultJSON)` line there. Because you should wait until the task is finished, now you try to parse the json when it is not downloaded yet. – vortexwolf Dec 28 '12 at 20:13
  • Add onPostExecute method but still have nullPointerException – user1107922 Dec 29 '12 at 13:09

3 Answers3

1


Why don't you JSONArray json = new JSONArray(resultJSON); do this on post execute method of async task .

And i will not suggest varevarao way , as it will create extra burden of one thread .

Code_Life
  • 5,742
  • 4
  • 29
  • 49
  • Add onPostExecute method but still have nullPointerException. – user1107922 Dec 29 '12 at 13:10
  • yes it will .. try to understand y ur getting null pointer as returning json just after calling async task .. u have change ur flow of code in such a way in post execute u return ... u can also refer this link http://stackoverflow.com/questions/8061571/how-use-progressdialog-and-async-task-get-method-simultaneously – Code_Life Dec 29 '12 at 17:40
0

You should use the get() method of the AsyncTask class to retrieve the result of the task. It waits for the task to complete and gets the result (which means it'd be best if you enclose it within a separate thread with a progress dialog or just a background thread).

public JSONArray getJSON(String url) throws JSONException {
    Parser parser = new Parser();
    parser.execute(url);
    resultJSON = parser.get(); // Probably put this in a Thread to avoid spending too much time waiting for a result on the main thread
    JSONArray json = new JSONArray(resultJSON);
    return json;
}
varevarao
  • 2,186
  • 13
  • 26
0

The problem is fixed. It's an awful workaround but it works. Add this line

while(json==null) {}

after calling the execute method.

user1107922
  • 610
  • 1
  • 12
  • 25