asqa
asqa

Reputation: 199

How to iterate all data SQLite and assign to Hashmap completely?

In my SQLite actualy there is 375 data, but when I try to iterate that data and assign to hashmap only 226 data successfully assigned, whats wrong with my code below?

public static HashMap<String, String> getLanguage() {
    HashMap<String,String> hashMap = new HashMap<>();
    Cursor cursor = database.query(DB_TABLE
            , null
            , null
            , null
            , null
            , null, _ID + " ASC"
            , null);
    //cursor.moveToFirst();
    System.out.println("Cursor count"+cursor.getCount());
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        hashMap.put(cursor.getString(cursor.getColumnIndex(KEY_LANG)), cursor.getString(cursor.getColumnIndex(STRING)));
    }
    return hashMap;
}

Upvotes: 0

Views: 132

Answers (1)

shmakova
shmakova

Reputation: 6426

You have more than one entry with one KEY_LANG. You can store list of STRING instead of one STRING in map value

public static HashMap<String, ArrayList<String>> getLanguage() {
    HashMap<String, ArrayList<String>> hashMap = new HashMap<>();
    Cursor cursor = database.query(DB_TABLE,
            null,
            null,
            null,
            null,
            null,
            _ID + " ASC",
            null);
    //cursor.moveToFirst();
    System.out.println("Cursor count" + cursor.getCount());
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        String key = cursor.getString(cursor.getColumnIndex(KEY_LANG));
        String value = cursor.getString(cursor.getColumnIndex(STRING));
        if (hashMap.containsKey(key)) {
            hashMap.get(key).add(value);
        } else {
            ArrayList<String> list = new ArrayList<>();
            list.add(value);
            hashMap.put(key, list);
        }
    }
    return hashMap;
}

Upvotes: 1

Related Questions