Abh*_*nav 0 android arraylist hashmap
我有价值观
问题Q-id
Q1 1
Q2 2
......依此类推
我想通过调用函数来检索它们.所以我使用了HashMaps的arraylist如下..
public ArrayList<HashMap<String,String>> getAllQuestions(Integer id)
{
try
{
HashMap<String,String> QuesList = new HashMap<String,String>();
ArrayList<HashMap<String, String>> QuestionArrayList = new ArrayList<HashMap<String, String>>();
// Select All Query
String selectQuery = <some query here>;
cursor = mDb.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do
{
QuesList.put("ques_id", cursor.getString(2));
QuesList.put("ques_text", cursor.getString(8));
QuestionArrayList.add(QuesList);
Log.i("ques",cursor.getString(8) );
} while (cursor.moveToNext());
}
Log.i("check"," Ques list returned");
return QuestionArrayList;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,Logcat显示在单个提取时成功检索所有问题(如Log.i语句所示),但是当我在结束时运行以下循环时,所有元素都被最后提取的问题替换.任何帮助深表感谢.
for(HashMap<String, String> t : QuesList )
{
Log.d("out there", "count" + t.getString());
Log.i("mapping....",t.get("ques_id"));
}
Run Code Online (Sandbox Code Playgroud)
调用add方法时,仅添加对对象的引用.因此,下次修改对象时,引用会引用已修改的对象,并且不会保留对象的旧状态.
在您的情况下,每次要将它们添加到以下内容时,您都必须创建新对象List:
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do
{
//Create a new object instance of the Map
HashMap<String,String> QuesList = new HashMap<String,String>();
QuesList.put("ques_id", cursor.getString(2));
QuesList.put("ques_text", cursor.getString(8));
QuestionArrayList.add(QuesList);
Log.i("ques",cursor.getString(8) );
} while (cursor.moveToNext());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1587 次 |
| 最近记录: |