0

I have script return JSON like this

{"a":"something","b":"something"}
{"a":"something1","b":"something1"}

It's NDJSON response! Now i am trying to retrieve it from android but i get null on jsonResult. This is the code I use after fetching:

JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = new JSONArray(jsonResponse);

I get null pointer exception on first line because jsonResult is null. What is wrong?

This is how i fetch:

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);

HttpResponse response = httpclient.execute(httpget);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
vitas_kek
  • 41
  • 7

2 Answers2

0

Check if result is null before using it

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(params[0]);

HttpResponse response = httpclient.execute(httpget);

jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

if(result != null) {
    JSONObject jsonResponse = new JSONObject(jsonResult);
    JSONArray jsonMainNode = new JSONArray(jsonResponse);
} else {
    //Do something
}

Now you have to check your request or the inputStreamToString method to know why you have a null response.

ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
0

Try This:

int status = response.getStatusLine().getStatusCode();
 HttpEntity httpEntity = response.getEntity();
            is = httpEntity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            is.close();
            String json = sb.toString();
JSONObject jObj = new JSONObject(json);
Mayuri Joshi
  • 164
  • 1
  • 2
  • 12