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

  • Did you checked [this](https://www.oracle.com/technical-resources/articles/java/json.html) instead of trying to do the json conversion by yourself ? – Ptit Xav Feb 27 '22 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 –  Feb 27 '22 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? – Moshe Katz Feb 27 '22 at 14:39
  • Yes I get this error `Value item1 at 0 of type java.lang.String cannot be converted to JSONObject` –  Feb 27 '22 at 14:43
  • Try just array.getString(i) – Ptit Xav Feb 27 '22 at 14:53

1 Answers1

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

Moshe Katz
  • 15,992
  • 7
  • 69
  • 116