I started a thread here about parsing a nested array: How do you return the contents of the following nested JSON Array in Android?
I'm downloading a list of subway stations in a line from the following url: https://api.tfl.gov.uk/Line/victoria/Route/Sequence/inbound?serviceTypes=Regular,Night
The stations are enclosed in a nested array. I need to extract "id" and "name" from the "stopPoint" array nested in the"stopPointSequences" array. I'm using AsyncTask and storing the list in a RecyclerView Adapter. I'm not using HashMap or GSON. Only one to four items are being displayed.
The app isn't crashing but the above index error is on this line(code below): JSONObject innerElem = stopPointArrayList.getJSONObject(i);
Also, the warning for the "for"statement above it is that it "statement has empty body". I came across this thread:
Error org.json.JSONException: Index 2 out of range
I changed "i" to "j" in the nested "for" statement, but "j" isn't recognized.
Thank you in advance.
To moderator. Is it alright if I post a link to my other thread and not copy and paste all of the code here?
JSONUtils class:
public static ArrayList<Stations> extractFeatureFromStationJson(String stationJSON)
{
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(stationJSON))
{
return null;
}
ArrayList<Stations> stations = new ArrayList<>();
try
{
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(stationJSON);
JSONArray stopPointSequenceArrayList = baseJsonResponse.getJSONArray("stopPointSequences");
if (stopPointSequenceArrayList != null)
{
for (int i = 0; i < stopPointSequenceArrayList.length(); i++)
{
JSONObject elem = stopPointSequenceArrayList.getJSONObject(i);
if (elem != null)
{
JSONArray stopPointArrayList = elem.getJSONArray("stopPoint");
if (stopPointArrayList != null) {
for (int j = 0; j < stopPointArrayList.length(); j++) ;
{
JSONObject innerElem = stopPointArrayList.getJSONObject(j);
if (innerElem != null) {
String idStation = "";
if (innerElem.has("id")) {
idStation = innerElem.optString(KEY_STATION_ID);
}
String nameStation = "";
if (innerElem.has("name")) {
nameStation = innerElem.optString(KEY_STATION_NAME);
}
Stations station = new Stations(idStation, nameStation);
stations.add(station);
}
}
}
}
}
}
} catch (JSONException e)
{
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing stations JSON results", e);
}
// Return the list of stations
return stations;
}
}