在每个hashmap变量中获得相同的值。为什么?
问题描述:
HashMap<String, String> map = new HashMap<>();
JSONObject jsonResponse = new JSONObject(response);
HashMap<String, String> question1 = readJsonObject(jsonResponse.getJSONObject("1"), map);
HashMap<String, String> question2 = readJsonObject(jsonResponse.getJSONObject("2"), map);
HashMap<String, String> question3 = readJsonObject(jsonResponse.getJSONObject("3"), map);
q1.setText(question1.get("question")); //q1,q2,q3 are textviews
q2.setText(question2.get("question"));
q3.setText(question3.get("question"));
这是readJsonObject方法/函数:
private HashMap<String,String> readJsonObject(JSONObject jsonObject,HashMap<String, String> map) throws JSONException {
map.put("question", jsonObject.getString("question"));
map.put("optiona", jsonObject.getString("optiona"));
map.put("optionb", jsonObject.getString("optionb"));
map.put("optionc", jsonObject.getString("optionc"));
map.put("optiond", jsonObject.getString("optiond"));
map.put("correct", jsonObject.getString("correct"));
return map;
}
但我得到在Q1 Q2 Q4 TextViews相同的字符串值。请解决这个问题。
响应从所述服务器获取:
{
"0":[],
"success":true,
"1":{ "question":"question3",
"optiona":"optiona",
"optionb":"optionb",
"optionc":"optionc",
"optiond":"optiond",
"correct":"optiona"},
"2":{ "question":"question1",
"optiona":"optiona",
"optionb":"optionb",
"optionc":"optionc",
"optiond":"optiond",
"correct":"optiond"},
"3":{ "question":"question4",
"optiona":"optiona",
"optionb":"optionb",
"optionc":"optionc",
"optiond":"optiond",
"correct":"optionc"}
}
获取从服务器不同的值响应但Q1,Q2,Q3表示相同的值。为什么?请解决此问题
如果我在每个readJsonObject()textview变为空白后添加map.clear(),并且如果我在readJsonObject()中添加map.clear,则q1,q2中的变化仍然不变, q3
如果我在每次调用readJsonObject获取正确答案时使用不同的hashmap,但我认为效率不高。对?
答
变化的方法来此
private HashMap<String,String> readJsonObject(JSONObject jsonObject) throws JSOException {
HashMap<String, String> tempMap = new HashMap<>();
tempMap.put("question", jsonObject.getString("question"));
tempMap.put("optiona", jsonObject.getString("optiona"));
tempMap.put("optionb", jsonObject.getString("optionb"));
tempMap.put("optionc", jsonObject.getString("optionc"));
tempMap.put("optiond", jsonObject.getString("optiond"));
tempMap.put("correct", jsonObject.getString("correct"));
return tempMap;
}
清除你进入readJsonObject –
如果我每天readJsonObject后加入map.clear()()的TextView变成空白,,,,,如果我添加地图HashMap中每次.clear in readJsonObject()在q1,q2,q3中没有改变仍然是相同的值 –
如果我在每次调用readJsonObject时都使用不同的hashmap得到正确的答案但我认为效率不高。对? –