我正在使用Json Asp.NET Webservice和Android Soap服务来检索数据
它工作正常。现在,我想在ArrayAdapter&中设置Spinner中的Value和Text。 GSON。怎么做 ?
我的代码:
placelist = gson.fromJson(result, City[].class);
ArrayAdapter<City> adapter = new ArrayAdapter<City>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, placelist);
spinnerFood.setAdapter(adapter);
我的输出:
[{"CityId":1,"CityName":"Vadodara"},{"CityId":2,"CityName":"ahmedabad"},{"CityId":3,"CityName":"Gandhinagar"},{"CityId":4,"CityName":"Bhavnagar"},{"CityId":7,"CityName":"Eluru"},{"CityId":8,"CityName":"Visakhapatnam"},{"CityId":15,"CityName":"Anantapur"},{"CityId":16,"CityName":"Srikakulam"}]
我想将CityName设置为Spinner Text,将CityId设置为Spinnet Value。 City是包含CityId和CityName参数的java类文件。
答案 0 :(得分:1)
如果您只希望CityName成为Spinner的下拉值
然后你应该只将CityName列表而不是City类的数组传递给适配器。 因此,要从数组中提取CityName,您可以这样做:
List lList = Arrays.asList(placelist);
List<String> cityName = new ArrayList<String>();
List<String> cityId = new ArrayList<String>();
City obj;
for (int i=0; i < lList .size(); i++)
{
obj= lList.get(i);
cityName.add(obj.getCityName());
cityId.add(obj.getCityId()); // City Id will be the value for on click of spinner items
}
现在您可以将此cityName列表传递给arrayadapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, cityName);
来到你问题的第二部分,你需要为spinner设置一个监听器,你可以从“cityId”数组列表中获得各个cityId的值
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
String Id;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
// TODO Auto-generated method stub
id= cityId.get(pos);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
让我知道它是否有效
此致
答案 1 :(得分:0)
请遵循以下教程Json parsing
首先在JsonArray和From数组中检索响应检索JsonObjects。并将它们存储在数组中,您可以将该值用于微调器