如何从firebase数据库

时间:2018-02-12 12:35:01

标签: java android firebase firebase-realtime-database firebase-authentication

获取消息方法

private void fetchMessages() {
    rootRef.child("Messages").child(MessageSenderId).child(MessageRecieverId)
            .addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                    Messages messages = dataSnapshot.getValue(Messages.class);
                    messagesList.add(messages);
                    messageAdapter.notifyDataSetChanged();
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {



                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    throw databaseError.toException();
                }
            });
}

定义ID

MessageSenderId = mAuth.getCurrentUser().getPhoneNumber();
MessageRecieverId = getIntent().getStringExtra("visit_user_id");

尝试制作基本的聊天应用 由于只有发件人id在rootref中被调用,所以我发送的消息r在d recyclerview中显示...我无法接收消息因为这...我怎样才能使它同时检索接收者ID和发送者ID时间

数据库结构

{
"Messages" : {
"+918105571584" : {
  "+919945342730" : {
    "-L58IPCLEeE21vH_-1Ry" : {
      "message" : "Hi",
      "seen" : false,
      "time" : 1518427022478,
      "type" : "text"
    },
    "-L58IU1VIHN0rHaUox3a" : {
      "message" : "Hello",
      "seen" : false,
      "time" : 1518427042257,
      "type" : "text"
    },
    "-L58IYN1GpHPdkWCY7Hn" : {
      "message" : "Hi",
      "seen" : false,
      "time" : 1518427060021,
      "type" : "text"
    }
  }
 },
"+919945342730" : {
  "+918105571584" : {
    "-L58IPCLEeE21vH_-1Ry" : {
      "message" : "Hi",
      "seen" : false,
      "time" : 1518427022478,
      "type" : "text"
    },
    "-L58IU1VIHN0rHaUox3a" : {
      "message" : "Hello",
      "seen" : false,
      "time" : 1518427042257,
      "type" : "text"
    },
    "-L58IYN1GpHPdkWCY7Hn" : {
      "message" : "Hi",
      "seen" : false,
      "time" : 1518427060021,
      "type" : "text"
    }
  }
}
},
"Users" : {
"+918105571584" : {
  "Email" : "",
  "Name" : "Akash",
  "Quote" : "",
  "Status" : ""
},
"+919945342730" : {
  "Email" : "",
  "Name" : "Sav",
  "Quote" : "",
  "Status" : ""
}
}
}

1 个答案:

答案 0 :(得分:0)

根据您的上一条评论,我了解您只能显示与单个用户相关的消息。用户只能看到他的消息,而不能看到其他用户消息。要解决此问题,您需要创建chat rooms,其中每个用户都可以添加所有聊天室成员都可以看到的消息。

因此,您需要更改数据库结构。使用实际的数据库无法实现这一目标。