0

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 onResponsemethod 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 
                }
1
  • your server is returning JSONArray and not JSONObject, so no need to convert it. Commented Feb 26, 2016 at 1:42

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.