[英]How to set Hashmap value using model class
I want to set Hashmap value using data from database and set it in model class, it doesn't work yet and shows empty data. 我想使用数据库中的数据设置Hashmap值并将其设置在模型类中,它尚不可用,并显示空数据。 Here is my code, get Data from database
这是我的代码,从数据库获取数据
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();
}
}
when I check it, Hashmap just shows empty data, Thank you! 当我检查它时,Hashmap只会显示空数据,谢谢!
I suppose your bug is here: 我想您的错误在这里:
if(categories.get(i).getId()==chatRoom.getId_kategori())
chatroom_list.add(chatRoom);
I guess getId() returns Integer
, which is an object. 我猜getId()返回
Integer
,这是一个对象。 Comparing objects with ==
fails in most cases. 在大多数情况下,用
==
比较对象失败。 When it comes to Integer
, it fails once the value is under -128 or over 127 (though this can be overriden. Also there are other circumstances when comparing integers using ==
can like magically fail or succed. Just don't do it). 当涉及到
Integer
,一旦值小于-128或大于127,它就会失败(尽管可以覆盖。也有其他情况,使用==
比较整数时可能会魔术般失败或成功。只是不要这样做) 。
Anyhow. 无论如何。 Check if
getId()
returns Integer
or Long
. 检查
getId()
返回Integer
或Long
。 If so, change it to categories.get(i).getId().equals(chatRoom.getId_kategori())
如果是这样,请将其更改为
categories.get(i).getId().equals(chatRoom.getId_kategori())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.