user903601
user903601

Reputation:

Populating a Spinner with a JSON Array

I have the following code populating a spinner,

JSONObject jsonResponse = new JSONObject(new String(buffer));
JSONArray myUsers = jsonResponse.getJSONArray("GetBusNamesResult");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Select a Buseness...");

for (int i = 0; i < myUsers.length(); ++i)
{
    //String jsonStr = myUsers.getString(i);
    //JSONObject myJsonObj = new JSONObject(jsonStr);
    //adapter.add(myJsonObj.getString("BusName"));
    adapter.add(myUsers.getString(i));
}

userSpinner.setAdapter(adapter);
userSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

With this JSON object,

{"GetBusNamesResult":[{"BusName":"Fred Camping","BusPhone":"0434943743"},{"BusName":"Joe's Carpets","BusPhone":"1234687965"}]}

But it displays the whole list for each record in the spinner like this,

{“BusName”:”Joe”,”BusPhone”:”1234567890”}

How can I fix that? I am able to put just the username into the spinner with the commented out code above but then get no return values.

Also is that returned JSON called an “Array List”???

Cheers,

Mike.

Upvotes: 2

Views: 5143

Answers (1)

Kurtis Nusbaum
Kurtis Nusbaum

Reputation: 30825

Change;

adapter.add(myUsers.getString(i));

to

adpater.add(myUsers.getJSONObject(i).getString("BusName");

To retrieve the bus phone once the bus name has been selected, store your bus name and bus phone values in a map as well. That way, when the bus name is selected, you can populate your widgets with the info from the map.

Upvotes: 4

Related Questions