JSON 解析迴圈中 fetchDatefromID.add(i, tempProgram),但 get(i) 取出的皆為最後一筆資料。
CustomerList tempProgram = new CustomerList(); // 迴圈外只建立一次
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
tempProgram.setCompanyName(json_data.getString("company"));
tempProgram.setID(json_data.getString("id"));
fetchDatefromID.add(i, tempProgram); // 每次加入同一物件參考
}
tempProgram 只實例化一次,迴圈每輪修改屬性並加入 List,導致 List 所有元素指向同一物件,最終皆呈現最後修改的值。
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
CustomerList tempProgram = new CustomerList(); // 每輪新建
tempProgram.setCompanyName(json_data.getString("company"));
tempProgram.setID(json_data.getString("id"));
fetchDatefromID.add(tempProgram); // 直接 add 尾端即可
}
fetchDatefromID.add(tempProgram) 取代 add(i, ...),避免索引管理錯誤