I have a ListView which I populate with data from a database.
ArrayList<HashMap<String, String>> userList = dBcode.getAllUsers();
ListAdapter adapter = new SimpleAdapter(
Main_Activity.this,userList, R.layout.list_view_search_item, new String[]
{ "name", "age", },
new int[] {R.id.name, R.id.Age});
It works perfectly well.
Now I want to create a new vResult for every row in the Listview with the values from the ListView, instead of typing it like the example below.
private Result[] resultArray = {
vResult("Thomas", "12"),
vResult("Mike", "15")};
This is the code to retrieve the data from the database.
public ArrayList<HashMap<String, String>> getAllUsers(){
ArrayList<HashMap<String, String>>userArrayList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM user ORDER BY name";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
HashMap<String, String> contactMap = new HashMap<String, String>();
contactMap.put("name", cursor.getString(0));
contactMap.put("age", cursor.getString(1));
userArrayList.add(contactMap);
} while(cursor.moveToNext());
}
return userArrayList;
}
Thanks
It would probably be easier for you if instead of using a HashMap, you created a class to hold your user fields (with getter/setter methods):
public class User {
private String mName;
private String mAge;
public User(String name, String age){
mName = name;
mAge = age;
}
public String getName(){
return mName;
}
public String getAge(){
return mAge;
}
public String setName(String name){
mName = name;
}
public String setAge(String age){
mAge = age;
}
}
And to create a User object from the database:
ArrayList<User> userArrayList = new ArrayList<User>();
...
contact = new User(cursor.getString(0), cursor.getString(1));
userArrayList.add(contact);
You can call adapter.getItem(position) to return the data object at a particular index:
User user = (User)adapter.getItem(0);
Then convert the data into whatever format you prefer. Maybe something like this:
private Result[] resultArray = new Result[1];
resultArray[0] = vResult(user.getName(), user.getAge());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With