I have values as
Question Q-id
Q1 1
Q2 2
…and so on
I want to retrieve them by calling a function. So i used an arraylist of HashMaps as follows..
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;
}
}
Now the Logcat shows that all questions are retrieved successfully at the time of individual fetch (as shown by the Log.i statement) but whe i run the following loop at the end all the elements are replaced by the last fetched question. Any help is much appreciated.
for(HashMap<String, String> t : QuesList )
{
Log.d("out there", "count" + t.getString());
Log.i("mapping....",t.get("ques_id"));
}
When you call the
addmethod, only the reference to the object is added. So next time you modify the object, the reference refers to the modified object and the old state of the object is not retained.In your case, you will have to create new objects every time you want to add them to the
List: