0

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!!

5
  • Did you checked this instead of trying to do the json conversion by yourself ? Commented Feb 27, 2022 at 12:13
  • Unlike the above article, the array I am fetching doesn't have any key:value pair. It's simply in this format ["item1","item2",...]. It's an indexed array Commented Feb 27, 2022 at 13:55
  • Since you are using e.printStackTrace(), have you checked logcat to see if there is an error? Or better, can you put in proper error handling to show an error message when the JSON parsing fails? Commented Feb 27, 2022 at 14:39
  • Yes I get this error Value item1 at 0 of type java.lang.String cannot be converted to JSONObject Commented Feb 27, 2022 at 14:43
  • Try just array.getString(i) Commented Feb 27, 2022 at 14:53

1 Answer 1

0

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

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

Comments

Your Answer

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