如何使用模型类设置Hashmap值

时间:2016-05-30 04:20:57

标签: java database class model hashmap

我想使用来自数据库的数据设置Hashmap值并将其设置在模型类中,它不起作用并显示空数据。这是我的代码,从数据库中获取数据

private ArrayList<Kategori> categories;
private ArrayList<ChatRoom> chatroom_list;
private HashMap<Integer, ArrayList<ChatRoom>> chatrooms;

void getDataList(){
    categories = new ArrayList<>();
    chatrooms = new HashMap<>();
    chatroom_list = new ArrayList<>();
    try{
        categories.clear();
        cursor = db.rawQuery("SELECT * FROM kategori ORDER BY id ASC", null);
        //cursor2 = db.rawQuery("SELECT * FROM chatroom ORDER BY id ASC LIMIT ", null);
        Kategori kategori;
        while (cursor.moveToNext()){
            kategori = new Kategori();
            kategori.setId(cursor.getInt(cursor.getColumnIndex("id")));
            kategori.setNama(cursor.getString(cursor.getColumnIndex("nama")));
            categories.add(kategori);
        }
        listAdapter.notifyDataSetChanged();
    }catch(Exception e){
        e.printStackTrace();
    }
    try{
        chatroom_list.clear();
        chatrooms.clear();
        ChatRoom chatRoom;
        for (int i=0;i<categories.size();i++){
            cursor2 = db.rawQuery("SELECT * FROM chatroom WHERE status = '0' ORDER BY id ASC", null);
            while (cursor2.moveToNext()){
                chatRoom = new ChatRoom();
                chatRoom.setId(cursor2.getInt(cursor2.getColumnIndex("id")));
                chatRoom.setNama(cursor2.getString(cursor.getColumnIndex("nama")));
                chatRoom.setDosen(cursor2.getString(cursor2.getColumnIndex("dosen")));
                chatRoom.setInfo(cursor2.getString(cursor2.getColumnIndex("info")));
                chatRoom.setId_kategori(cursor2.getInt(cursor2.getColumnIndex("id_kategori")));
                if(categories.get(i).getId()==chatRoom.getId_kategori())
                    chatroom_list.add(chatRoom);
            }
            chatrooms.put(categories.get(i).getId(), chatroom_list);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

当我检查它时,Hashmap只显示空数据,谢谢!

1 个答案:

答案 0 :(得分:0)

我想你的错误就在这里:

if(categories.get(i).getId()==chatRoom.getId_kategori())
    chatroom_list.add(chatRoom);

我猜getId()返回Integer,这是一个对象。在大多数情况下,将对象与==进行比较会失败。当涉及到Integer时,它会在值低于-128或超过127时失败(尽管可以覆盖它。还有其他情况,使用==比较整数可能会神奇地失败或成功。只是不要这样做)。

总之。检查getId()是否返回IntegerLong。如果是,请将其更改为categories.get(i).getId().equals(chatRoom.getId_kategori())