I need to parse json
from String builder
, but I get this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
I don't know why stringBuilder.toString()
give me the array with objects!
Here is my code:
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// return stringBuilder.toString();
System.out.println("EHEH"+stringBuilder.toString());
JSONArray mainObject = null;
try {
mainObject = new JSONArray(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < mainObject.length(); i++) {
JSONObject object = null;
try {
object = mainObject.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Video video=new Video();
String url = object.getString("url");
String titolo = object.getString("titolo");
String sottotitolo = object.getString("sottotitolo");
String data = object.getString("date");
//video.setId(idd4);
System.out.println("CAZZO:"+video.getId());
video.setPic(url);
video.setTitolo(titolo);
video.setSottotitolo(sottotitolo);
video.setData(data);
videoList.add(video);
} catch (JSONException e) {
e.printStackTrace();
}
}
Can someone help me?
JSON RESPONSE: