Gideon Steven Tobing Gideon Steven Tobing - 1 year ago 138
Android Question

How to Get String from Json Array

its actually a simple code, cuz of lack of basic I still cant manage to handle this.

After I made a Post JSON Method on my own Api, I get the following response


What I'm trying to achieve is that I would like to get the value of this "id" which is "2".

I've tried the following code in my private void method

private void getUserID() {

StringRequest stringRequest = new StringRequest(Method.POST,Constants.GET_USER_ID,
new Response.Listener<String>() {
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();

try {
JSONObject jsonRootObject = new JSONObject(strJson);

//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("");

//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);

int id = Integer.parseInt(jsonObject.optString("id").toString());
String idUser = jsonObject.optString("id").toString();

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

new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();


protected Map<String, String> getParams() throws AuthFailureError {

Map<String, String> map = new HashMap<>();

map.put(Constants.KEY_A, username);
map.put(Constants.KEY_B, password);

return map;
RequestQueue requestQueue = Volley.newRequestQueue(this);

I get it from here.

It's a bit of waste, because I only have one list object in my array, and I thinks for loop is not really important in here.

Answer Source

replace your try block with following

  try {
             JSONArray  jsonArray = new JSONArray(response);

                JSONObject jsonObject = jsonArray.getJSONObject(0);
                String idUser = jsonObject.getString("id");
                Log.e("id is: ", idUser);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download