Question

I have a database which i select 2 strings one as an item other one is description.I am trying to map these 2 strings into a listview item-subitem layout. the following code is what i tried so far.

List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> datum = new HashMap<String, String>(2);
SimpleAdapter adapter = new SimpleAdapter(this, data,
        android.R.layout.simple_list_item_2, 
        new String[] { "item","descr" }, 
        new int[] { android.R.id.text1, android.R.id.text2 });
itemList.setAdapter(adapter);

Cursor cours = MainActivity.mydb.query("sub_menu", null, "cat_id = "
        + menuid + " AND sub_flag = 1", null, null, null, null);

if (cours.moveToFirst()) {
    do {
        datum.put("item", cours.getString(cours.getColumnIndex("sub_label")));
        datum.put("descr", cours.getString(cours.getColumnIndex("sub_description")));
        data.add(datum);
        Log.d("testt", datum.toString());

        adapter.notifyDataSetChanged();

    } while (cours.moveToNext());
}

the problem now it will add 5 entries to the listview with the same values which are the last row selected form the database which is not what. any idea how to fix this ?

EDIT. after experimenting with it i found that i was overwriting the object datum which end up having the save value for all the entries. the fix was as easy as moving the intializition line for datum into the loop. here is the final code

List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        String[] from = new String[] { "rowid", "col_1" };
        int[] to = new int[] { android.R.id.text1, android.R.id.text2 };

        Cursor cours = MainActivity.mydb.query("sub_menu", null, "cat_id = "
                + menuid + " AND sub_flag = 1", null, null, null, null);

        if (cours.moveToFirst()) {

            do {
                Map<String, String> datum = new HashMap<String, String>(2);
                datum.put("rowid",
                        cours.getString(cours.getColumnIndex("sub_label")));
                datum.put("col_1", cours.getString(cours
                        .getColumnIndex("sub_description")));
                data.add(datum);
            } while (cours.moveToNext());

        }
        SimpleAdapter adapter = new SimpleAdapter(this, data,
                android.R.layout.simple_list_item_2, from, to);
        itemList.setAdapter(adapter);
Was it helpful?

Solution

make custom ListView and use CursorAdapter Here is a good example will help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top