Can Talay Can Talay - 6 months ago 56
Android Question

JsonArray null pointer exception Android

I try to take movies data with JSONarray. What would be the best way to parse this in an Android app? I am getting java.lang.NullPointerException when I run the activity. Please take a look at my code and let me know if you have any suggestions.
This Json data

{"Search":[{"Title":"Life of Pi","Year":"2012","imdbID":"tt0454876","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTg2OTY2ODg5OF5BMl5BanBnXkFtZTcwODM5MTYxOA@@._V1_SX300.jpg"},
{"Title":"Life Is Beautiful","Year":"1997","imdbID":"tt0118799","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTQwMTM2MjE4Ml5BMl5BanBnXkFtZTgwODQ2NTYxMTE@._V1_SX300.jpg"}],"totalResults":"9675","Response":"True"}


My Java code here;

@Override
protected String doInBackground(String... voids) {
String seriesUrl = "http://www.omdbapi.com/?s="+voids[0]+"&y=&plot=short&r=json";
Log.e("seriesurl:", seriesUrl);
JSONObject jsonRootObject=null;
JSONArray jsonArray=null;
JSONObject jsonObject=null;
try {

String json = seriesParser.getJSONFromUrl(seriesUrl);
//JSONArray jsonArray= jsonObject.optJSONArray("Search");
try {
jsonArray =jsonRootObject.optJSONArray("Search");
// jsonObject = new JSONObject(json);
for (int i=0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);

}



}catch (JSONException e){
e.printStackTrace();
}
//JSONArray listArray = jsonObject.getJSONArray("Title");
//JSONObject firstObj = jsonObject.getJSONObject("Title");
title = jsonObject.getString("Title");
genre = jsonObject.getString("Genre");
year = jsonObject.getString("Year");
resim = jsonObject.getString("Poster");

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

return null;
}


Edit;
My code working perfectly in here;

try {
String json = seriesParser.getJSONFromUrl(seriesUrl);
JSONObject jsonResponse = new JSONObject(json);
JSONArray jsonMainNode = jsonResponse.optJSONArray("Search");

for(int i = 0; i<jsonMainNode.length();i++){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
title = jsonChildNode.optString("Title");
genre = jsonChildNode.optString("Genre");
year = jsonChildNode.optString("Year");
resim = jsonChildNode.optString("Poster");
}


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

Answer
jsonArray =jsonRootObject.optJSONArray("Search");

jsonRootObject is null

So add this line before it :

jsonRootObject = new JSONObject(json)