Reputation: 5557
I have a JSONObject
of the following format:
[{"ascii_name":"Rio de Janeiro"},{"ascii_name":"Riyadh"},{"ascii_name":"Rome"},{"ascii_name":"Rawalpindi"},{"ascii_name":"Rabat"},{"ascii_name":"Recife"},{"ascii_name":"Ra's Bayrut"},{"ascii_name":"Rajkot"}]
which has been created using the following code:
while($row = $all_cities->fetch_array())
{
$myArray["ascii_name"] = $row["ascii_name"];
$returnArray[] = $myArray;
}
echo json_encode($returnArray);
Now I am using a Volley
task to load this into my Android app. In the onResponse
method I want to obtain each of the city names and load it into an ArrayList<String>
using a for
loop. This is my code now, however it won't work since s
is a JSONObject
not a JSONArray
.
@Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
for (int i = 0; i < jsonObject.length(); i++) {
JSONObject a = jsonObject.getJSONObject(i);
....... more code which isn't relevant
}
Upvotes: 0
Views: 73
Reputation: 3520
Instead of
JSONObject jsonObject = new JSONObject(s);
use
JSONArray jsonArray = new JSONArray(s);
Also i think you are using StringRequest in Volley. Switch to JSONObjectRequest in Volley.
Upvotes: 2
Reputation: 15798
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
But make sure you do you have correct JSON response. You can do that by printing your json using Log.d before you parse it.
Upvotes: 0