Reputation: 5063
I did have a look at spinners, but in the program that I am working on the data on the spinner is loaded from an API ... Being new, I sort of don't have any idea on loading the JSONObjects onto the spinner. Help please.
The API reply is sort of like this :
{"status":"","data":{"1":"scorpio"},"message":""}
Where I would have to display the value "Scorpio" the spinner and at the backend assign the value "1" while passing the form. Help please.
Upvotes: 0
Views: 542
Reputation: 21
Put your JSON array into array and simple assign to spinners in loop:
//json array
{"Employee":[{"Id":73,"Name":"Bård Pedersen","Email":"[email protected]","Mobile":"9004422"}]}
ArrayList<String> TAG_ID = new ArrayList<String>();
ArrayList<String> TAG_NAME = new ArrayList<String>();
ArrayList<String> TAG_EMAIL = new ArrayList<String>();
ArrayList<String> TAG_PHONE_MOBILE = new ArrayList<String>();
// Getting Array of Employee
employee = json.getJSONArray("Employee");
// looping through All Employee
for (int i = 0; i < employee.length(); i++) {
JSONObject c = employee.getJSONObject(i);
// Storing each json item in variable
id = c.getString("Id");
name = c.getString("Name");
email = c.getString("Email");
mobile = c.getString("Mobile");
// adding all get values into array
if (name != "null" && mobile != "null") {
TAG_NAME.add(name);
TAG_ID.add(id);
TAG_EMAIL.add(email);
TAG_PHONE_MOBILE.add(mobile);
close.add(R.drawable.close);
}
Upvotes: 2
Reputation: 3117
If your data is in the following way
{"data":[{"1":"scorpio"},{"2":"BMW"},{"3":"Scoda"}]}
then you retrieve and show that in the spinner as follows:-
String[] id,name;
JSONObject jObject = new JSONObject(your data);
JSONObject jdata = jObject.getJSONArray("data");
id = new String[jdata.length()];
name = new String[jdata.length()];
Iterator<?> keys = jSEngineers.keys();
for(int i=0;i<jdata.length();i++){
id[i] = (String) keys.next();
name[i] = (String) jSEngineers.getString(id[i]);
}
Now you can get those values into the specified arrays.Now you can assign required one to Spinner.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(YourActivity.this,android.R.layout.simple_spinner_item, name);
spinnerName.setAdapter(adapter);
now you can get selected spinner item as follows
spinnerName.getSelectedItemPosition();
with this you will get the position of the item.with the help of that you can retrieve your required id that is for your background purpose.As follows..
Log.i("Item id is",id[spinnerName.getSelectedItemPosition()].toString());
Upvotes: 1