我已从JSON
解析了一些PHP
数据,并将其显示为Spinner
。数据附带Key-Value。所以我将Hashmap
与SimpleAdapter
一起使用。 Spinner仅显示值。当用户选择一个项目时,该密钥将存储在MySQL
。
这是我的JSON
,
{
"32":"Western Food",
"33":"Chinese Food",
"34":"Mix Food",
"35":"Japanese Food",
"36":"Korean Food",
"37":"Italian Food",
"38":"German Food",
"45":"Muslim food ",
"46":"Indian food"
}
例如
活动A
用户添加新类别,他们选择" Mix Food"。当他们点击提交按钮时,键 - " 34"将存储在数据库中。
活动B
int get_selected_item_id=34;
List<HashMap<String, String>> category_arraylist = new ArrayList<HashMap<String, String>>();
Iterator<String> iterator = jsonObject1.keys();
while (iterator.hasNext()) {
String id = iterator.next();
String name=jsonObject1.getString(id);
HashMap<String, String> map = new HashMap<>();
map.put("id",id);
map.put("name",name);
category_arraylist.add(map);
}
String[] from = {"name"};
int[] to = {android.R.id.text1};
final SimpleAdapter adapter = new SimpleAdapter(item_edit.this, category_arraylist, android.R.layout.simple_spinner_dropdown_item, from, to);
category.setAdapter(adapter);
category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
category.setSelection(get_selected_item_id); // doesn't work
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
如果在微调器开始显示时,如何在活动B中将此项显示为默认值?
答案 0 :(得分:2)
为您的JSON
数据
private class Item {
String key;
String value;
public Item(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
将您的数据解析为此模型类
List<Item> list = new ArrayList<>();
Iterator<String> iterator = jsonObject1.keys();
while (iterator.hasNext()) {
String id = iterator.next();
String name = jsonObject1.getString(id);
list.add(new Item(id, name));
}
初始化Spinner
,
final ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this, android.R.layout.simple_spinner_dropdown_item, list);
category.setAdapter(adapter);
在get_selected_item_id
中找到list
的索引,并使用setSelection
的{{1}}方法将其设置为默认值。
Spinner
int index = findIndexOf(list, get_selected_item_id);
if (index != -1) {
category.setSelection(index);
}
方法,
findIndexOf
private int findIndexOf(List<Item> list, int selectedKey) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getKey().equals(String.valueOf(selectedKey))) {
return i;
}
}
return -1;
}
,
ItemSelectedListener