Currently I am able to populate my spinner two ways one way gives me results from the database which is what I need but the text in the spinner is in JSON format, it all works but it looks bad, then if I extract the name from the JSON and use it I lose the value part of the name value pair.
I’ve been informed that I need to use a BaseAdapter subclass to be able to do what I need to do. The code below works just like I would love it to but the data is hard coded in, which is no use.
What I want to do is fill MyData below with the JSON data returned from the database.
This code:
final MyData items[] = new MyData[4];
items[0] = new MyData( "Ken's Plimbing","125738468");
items[1] = new MyData( "Peninsula Pests","3787906453");
items[2] = new MyData( "Joe's Electrical","129754354");
items[3] = new MyData( "Garderning Supplies","097803452");*/
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(PropertyManagement.this, android.R.layout.simple_spinner_item, items );
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
userSpinner.setAdapter(adapter);
userSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
MyData d = items[position];
Toast.makeText(PropertyManagement.this, d.getValue(), Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
With this BaseAdapter:
class MyData {
public MyData( String spinnerText, String value ) {
this.spinnerText = spinnerText;
this.value = value;
}
public String getSpinnerText() {
return spinnerText;
}
public String getValue() {
return value;
}
public String toString() {
return spinnerText;
}
String spinnerText;
String value;
Works!
But I need to fill MyData with the JSON array returned from the database. I have been doing that with the following as per the first paragraph in this post.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PropertyManagement.this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
final MyData items[] = new MyData[4];
for (int i = 0; i < myUsers.length(); ++i)
{
adapter.add(myUsers.getJSONObject(i).getString("BusinessName"));
};
userSpinner.setAdapter(adapter);
The JSONArray/string looks like this,
{"BusinessName":"Petes Plumbing","BusinessPhone":"0434943743"},{"BusinessName":"Joes Electrical","BusinessPhone":"0466367279"}
Any help would be greatly appreciated.
Cheers,
Mike.
You are super close here, instead of adapter.add in your for loop you need to add it to items. Refactor like this:
What is different here is your finding the length of your JSONArray, creating a new array of MyItem of that size. Then you initialize the items with new MyItems based on values from your JSONArray. Finally, you are creating the adapter with items just like you did in the first example. I’m assuming in this example that myUsers in a JSONArray.