{
"chat_room" : {
"-Kp_ldAz7_g3W4riNkJY" : {
"message" : "Hello!",
"uname" : "Praveen"
}
}
}
这是我的Firebase DB jSON文件,用于一条聊天消息,我尝试了以下创建的名为“ appendChat()”的方法来在ListView上填充数据库。
但由于某种原因,ListView只显示最后发送的消息
private void appendChat(DataSnapshot dataSnapshot) {
final ArrayList<String> chatListArr = new ArrayList<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()) {
chatListArr.add((String) ((DataSnapshot) i.next()).getValue());
chatListArr.add((String) ((DataSnapshot) i.next()).getValue());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(getActivity().getApplicationContext(), android.R.layout.simple_list_item_2,android.R.id.text1, chatListArr);
chatList.setAdapter(arrayAdapter);
}
我的ListView有一个用于用户名的字符串和一个用于消息的子字符串,我如何更改代码以检索数据库值并在ListView中填充为
username:
message
最佳答案
问题在于,每次接收到消息时,您都在创建一个全新的ArrayAdapter
。这将有效删除所有先前的消息。我建议您在ArrayAdapter
中创建一次onCreate()
。然后,您可以将数据添加到ArrayList
并在适配器上调用notifyDataSetChanged()
。