How can i iterate over all of the "listPages" in this JSON object?
{
"listPages": [
{
"title": "Accounts",
"recordType": "Company",
},
{
"title": "Contacts",
"recordType": "Person",
}
]
}
I'm trying to add list items to a list from each item in the listPages array via this code:
JSONObject JSONConfig = envConfig.getEnvConfig(this);
try{
JSONArray listPages = JSONConfig.getJSONArray("listPages");
for(int i = 0 ; i < listPages.length() ; i++){
listItems.add(listPages.getJSONObject(i).getString("title"));
}
adapter.notifyDataSetChanged();
}catch(Exception e){
e.printStackTrace();
}
I can see in logcat that i'm getting a system error: "java.lang.NullPointerException" on the following line.
JSONArray listPages = JSONConfig.getJSONArray("listPages");
I've tried reading and tweaking things from other questions but i can't figure it out. Help would be much appreciated.
here is my envConfig.java class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class EnvConfig {
private String rawJSONString;
private JSONObject jsonObjRecv;
public JSONObject getEnvConfig(Context context){
InputStream inputStream = context.getResources().openRawResource(
R.raw.envconfigg);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
rawJSONString = sb.toString();
try {
JSONObject jsonObjRecv = new JSONObject(rawJSONString);
Log.i("Test", "<JSONObject>\n" + jsonObjRecv.toString()
+ "\n</JSONObject>");
} catch (Exception e) {
e.printStackTrace();
}
return jsonObjRecv;
}
}
envConfig.getEnvConfig(this);
? Have you verified that it is returning a validJSONArray
object?envConfig.getEnvConfig(this);
. Print out the value you get from this method prior to entering your for loop.