Search code examples
androidsimpleadapter

Must the Map be defined again and again?


I was intended to load datas from databases to ListView with SimpleAdapter, just as:

private void loadData() {
        // TODO Auto-generated method stub
        Cursor cursor = mHelper.getReadableDatabase().rawQuery(
                "select * from dict", null);
        int wordIndex = cursor.getColumnIndex("word");
        int detailIndex = cursor.getColumnIndex("detail");
        int flagIndex = cursor.getColumnIndex("flag");
        **(1)**//Map<String,String>map = new HashMap<String,String>();
        //map defined here, items are all the last record

        for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
            **(2)**Map<String,String>map = new HashMap<String,String>();
            if(cursor.getString(wordIndex)==null) break;
//          Log.d(tag,"word: "+cursor.getString(wordIndex));
            map.put("word", cursor.getString(wordIndex));
//          Log.d(tag,"detail: "+cursor.getString(detailIndex));
            map.put("detail", cursor.getString(detailIndex));   
//          Log.d(tag,"flag: "+cursor.getString(flagIndex));
            map.put("flag", cursor.getString(flagIndex));
            listItems.add(map);
        }
        cursor.close();
    }

listItems is defined as ArrayList<Map<String, String>> listItems;

when I defined the Map as 1, where the map is outside the for cycle, listItems keep listItems.length records of the final one, while the map is defined as 2, listItems keep listItems.length record as the database. Could someone just tell why? I will appreciate your answers!


Solution

  • The correct way to do this the second way i.e 2 .

    The reason is in each iteration a new object of Map<String,String> type is created and hence a fresh item is added to your ArrayList in each iteration when you use way 2.

    But in the first way, i.e. 1 in each iteration no new object is created as it was done only once before the for loop.And hence you don't get what you want.