-7

So I have this PHP file that returns a JSONArray.

[
  {
    "name": "SAMPLE NAME 1",
    "number": "12345",
    "entity": "User"
  },
  {
    "name": "SAMPLE NAME 2",
    "number": "67890",
    "entity": "Admin"
  }
]

I am using android volley for my android app. I would like to show a Toast that will show those names separately.

This is my android code:

StringRequest stringReq = new StringRequest(Request.Method.POST, "http://myfile.php", new Response.Listener<String>() 
{
        @Override
        public void onResponse(String response) {
            try {
                JSONObject json = new JSONObject(response);
                Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
Maraboc
  • 10,550
  • 3
  • 37
  • 48
nooooob
  • 1
  • 8
  • Can you tell us what's not working? – WasteD Oct 13 '17 at 07:18
  • 2
    your response is a json array not json object. – Vivek Mishra Oct 13 '17 at 07:18
  • 2
    Possible duplicate of [How to parse JSON in Android](https://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) – UltimateDevil Oct 13 '17 at 07:20
  • To get a specific JSONArray: JSONArray jArray = jObject.getJSONArray("ARRAYNAME"); To get the items from the array for (int i=0; i < jArray.length(); i++) { try { // Pulling items from the array String name = oneObject.getString("name"); String number = oneObject.getString("number"); } catch (JSONException e) { // Oops } } – UltimateDevil Oct 13 '17 at 07:23
  • https://www.androidhive.info/2014/05/android-working-with-volley-library-1/ For help follow this tutorial – Parth Goswami Oct 13 '17 at 07:23

4 Answers4

0

Your Reponse is in JSONArray and you trying to parse in JSONObject

try this to Parse your JSON

 try {

        JSONArray jsonArray = new JSONArray("response");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String name = object.getString("name");
            String number = object.getString("number");
            String entity = object.getString("entity");

        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
0

Try to use JsonArrayRequest this one

        JsonArrayRequest req = new JsonArrayRequest("your url goes here",
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());

                try {

                    jsonResponse = "";
                    for (int i = 0; i < response.length(); i++) {

                        JSONObject jObject = (JSONObject) response
                                .get(i);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),
                            "Error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
             }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
Navneet Krishna
  • 5,009
  • 5
  • 25
  • 44
0
 try {

    JSONArray j = new JSONArray("response");
    for (int i = 0; i < j.length(); i++) {
        JSONObject object = j.getJSONObject(i);
        String name = object.getString("name");
        String number = object.getString("number");
        String entity = object.getString("entity");

    }

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

Your response data is an array. You need parse to a JSONArray like below:

JSONArray jsonArray = new JSONArray(response);

if you want to read data by key you can do like below:

for (int index = 0; index < jsonArray.length(); index++) {
    JSONObject object = jsonArray.optJSONObject(index);
    if (object != null) {
        String name = object.optString("name");
        String number = object.optString("number");
        String entity = object.optString("entity");
    }
}

But now I offen using Gson to Parse data to a object. See next.

Step 1: Add the following line to your Gradle configuration

dependencies {
  compile 'com.google.code.gson:gson:2.8.0'
}

Step 2: Define UserModel class like this

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class UserModel {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("number")
    @Expose
    private String number;
    @SerializedName("entity")
    @Expose
    private String entity;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getEntity() {
        return entity;
    }

    public void setEntity(String entity) {
        this.entity = entity;
    }

}

Step 3: On the onResponse method change to bellow:

Gson gson = new GsonBuilder().create();
ArrayList<UserModel> models = gson.fromJson(response, new TypeToken<ArrayList<UserModel>>() {
}.getType());

now you can access your data like this

if (models != null && models.size() > 0) {
    for (int i = 0; i < models.size(); i++) {
        UserModel user = models.get(i);
        user.getName();
        user.getEntity();
        user.getNumber();
    }
}
Cuong Do
  • 48
  • 4