Skip to content
Advertisement

How do I fetch a JSON array from PHP to my java code?

My JSON response is like this:

["item1","item2",...]

Now, I want to add each of the array items into my spinner:

@Override
public void onResponse(Call<String> call, Response<String> response) {
    if (response.body() != null) {
       String[] arr=response.body().split(",");
       arr[0]=arr[0].replace("[","");
       arr[arr.length-1]=arr[arr.length-1].replace("]","");
       Arrays.sort(arr);
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_spinner_item,arr);                     
       adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
       if (qrtr_reg != null) {
          qrtr_reg.setAdapter(adapter);
       }
    }
}

All my spinner items are in double quotes(“”), which I don’t want. I want them in object format. How do I fix this?

EDIT: Tried the following code:

ArrayList<String> arr=new ArrayList<String>();
JSONArray array = null;
try {
    array = new JSONArray(response.body());
    for(int i=0;i<array.length();i++){                   
       arr.add(String.valueOf(array.getJSONObject(i).getString(0)));
    }
} catch (JSONException e) {
    e.printStackTrace();
}
Collections.sort(arr);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_spinner_item,arr);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
if (qrtr_reg != null) {
   qrtr_reg.setAdapter(adapter);
}

Now, my spinner is completely empty!!

Advertisement

Answer

Your second piece of code is almost correct. Here is the mistake:

arr.add(String.valueOf(array.getJSONObject(i).getString(0)))

Your array is not an array of JSON objects, it is an array of strings directly. Therefore, here is what that line should look like:

arr.add(array.getString(i))

(I’m guessing you copied your attempt from this answer, but the question there has an array of objects, and your array is much simpler.)

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement