我正在编写一个程序,其中我需要来自firebase的值,这些值完全插入,但我无法读取它。下面是我读取数据的方法。请告诉我哪里出错了。
private void displayChatMessage()
{
ListView listOfMessage = (ListView) findViewById(R.id.listview);
adapter = new FirebaseListAdapter<ChatMessage>(MainActivity.this, ChatMessage.class, R.layout.list_item, FirebaseDatabase.getInstance().getReference()) {
@Override
protected void populateView(final View v, final ChatMessage model, final int position)
{
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("mychatapp-409f8").child("data");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ChatMessage model = dataSnapshot.getValue(ChatMessage.class);
TextView messageText, messageUser, messageTime;
messageText = (TextView) v.findViewById(R.id.msg_body);
messageUser = (TextView) v.findViewById(R.id.msg_user);
messageTime = (TextView) v.findViewById(R.id.msg_time);
messageText.setText(model.getmsgbody);
messageUser.setText(model.getUname());
messageTime.setText(DateFormat.format("dd-MM-yyyy(hh:mm a)", model.getMtime()));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
listOfMessage.setAdapter(adapter);
}
And my demo class is
public class ChatMessage
{
public String user;
public long mtime;
public String msgbody;
public String uname;
public ChatMessage(String user, String msgbody,String name)
{
this.user = user;
this.msgbody = msgbody;
this.uname = name;
mtime = new Date().getTime();
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public ChatMessage() {
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public long getMtime() {
return mtime;
}
public void setMtime(long mtime) {
this.mtime = mtime;
}
public String getMsgbody() {
return msgbody;
}
public void setMsgbody(String msgbody) {
this.msgbody = msgbody;
}
}
我的firebase层次结构如下:
答案 0 :(得分:1)
我仍然需要包含R.id.msg_body
,R.id.msg_user
等的布局xml文件的名称。但是如果我们认为布局名称是R.layout.your_layout
,那么您的代码应如下所示:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("data");
adapter = new FirebaseListAdapter<ChatMessage>(MainActivity.this, ChatMessage.class, R.layout.your_layout, ref) {
@Override
protected void populateView(final View v, final ChatMessage model, final int position) {
TextView messageText, messageUser, messageTime;
messageText = (TextView) v.findViewById(R.id.msg_body);
messageUser = (TextView) v.findViewById(R.id.msg_user);
messageTime = (TextView) v.findViewById(R.id.msg_time);
messageText.setText(model.getmsgbody);
messageUser.setText(model.getUname());
messageTime.setText(DateFormat.format("dd-MM-yyyy(hh:mm a)", model.getMtime()));
}
};
listOfMessage.setAdapter(adapter);
希望这有帮助
注意:这只是一个疯狂的猜测,我想在评论中写它,因为我不确定它是否会起作用,但我认为评论字段是不够的