我有一个JSON:
{"results":[
{"id":"21","name":"Jonny"},
{"id":"22","name":"Samuel"},
{"id":"23","name":"Martha"}
]}
我需要将“name”放入 autocompletetextview 。
我需要根据autocompletetextview中的选定名称将“id”发布到其他活动。
请提前帮助,请提供帮助
答案 0 :(得分:0)
首先将json转换为hashmap:
HashMap<String, Integer> result = readJson("Your json string here");
public HashMap<String, Integer> readJson(String json) {
try {
JSONObject jsonObj = new JSONObject(json);
// Getting JSON Array node
JSONArray results = jsonObj.getJSONArray("results");
final int j = results.length();
HashMap<String, Integer> resultMap = new HashMap<>(j);
for (int i = 0; i < j; i++) {
JSONObject item = results.getJSONObject(i);
resultMap.put(item.getString("name"), item.getInt("id"));
}
return resultMap;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
现在设置自动完成适配器,如:
autoComplete.setAdapter(new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, new ArrayList<>(result.keySet())));
public void startNextActivity(int id) {
Intent intent = new Intent(getContext(), NextActivity.class);
intent.putExtra("id", id);
getContext().startActivity(intent);
}
将启动活动称为:
startNextActivity(result.get(autoComplete.getText().toString()));