How do I inflate a spinner from an array parsed with GSON
I'm new to the GSON library, I have a json data structure that looks like this.
{"networks":[{"networkId":0,"networkName":"Friends"},{"networkId":"1","networkName":"something"},{"networkId":"4","networkName":"a second thing"},{"networkId":"28","networkName":"another network"},{"networkId":"2","networkName":"blah"}]
I get this data through the following request
RestClient client = new RestClient();
client.setDebug();
client.AddParam("method", "get_user_networks");
client.AddParam("session_key", sessionKey);
client开发者_StackOverflow社区.Execute();
String response = client.getResponse();
NetworksData retval = null;
Gson gson = new Gson();
retval = gson.fromJson(response, NetworksData.class);
the Networks data class looks like this
public class NetworksData {
private List<Network> networks;
private List<Group> groups;
public List<Network> getNetworks() {
return this.networks;
}
public List<Group> getGroups() {
return this.groups;
}
public void setNetworks(List<Network> networks) {
this.networks = networks;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
}
and the invididual network class is the following
public class Network {
private String networkName;
private Integer networkId;
public String getName(){
return this.networkName;
}
public Integer getId(){
return this.networkId;
}
public void setName(String nameIn){
this.networkName = nameIn;
}
public void setId(Integer idIn){
this.networkId = idIn;
}
}
I'm trying to inflate a spinner with the network names, I can manually traverse the array and build a String array and inflate it that way, but that seems counter intuitive to the whole object model. Isn't there a way to get the list directly into the spinner?
Here is a way that works but is wrong
networkItems = new String[total];
// networks
if (retval.getNetworks().size() > 0) {
for (Network network : retval.getNetworks()) {
networkItems[i] = network.getName();
i++;
}
}
and then inflate the spinner like so
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, networkItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
networkSpinner.setAdapter(adapter);
Build your custom Adapter using your nerworks list or NetworksData object. You can subclass BaseAdapter to implement the Adapter (note that you can also subclass or compose with ArrayAdapter (or any other implementation) to reuse it).
精彩评论