Firebase查询不显示聊天

时间:2018-09-02 06:00:55

标签: android firebase firebase-realtime-database firebaseui

我有一个聊天应用程序的方法,一切似乎都正常运行,但是每次我尝试键入内容时,都不会弹出。

用户登录时,onActivityResult显示成功消息:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == SIGN_IN_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Snackbar.make(activity_main, "Success. Welcome.", Snackbar.LENGTH_SHORT).show();
        }
        else {
            Snackbar.make(activity_main, "Error", Snackbar.LENGTH_SHORT).show();
            finish();
        }
    }
}

但是,在以下情况下,它不会显示我的onCreate欢迎消息:

if(FirebaseAuth.getInstance().getCurrentUser() == null) {
    startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_REQUEST_CODE);
}
else {
    Snackbar.make(activity_main, "Welcome " + FirebaseAuth.getInstance().getCurrentUser().getEmail(), Snackbar.LENGTH_SHORT);
    //Load content
    displayChat();
}

键入消息时,也不会显示任何内容。我查询不正确吗?

private void displayChat() {

    ListView listOfMessage = findViewById(R.id.list_of_message);

    Query query = FirebaseDatabase.getInstance().getReference();
    FirebaseListOptions<Chat> options = new FirebaseListOptions.Builder<Chat>()
            .setLayout(R.layout.list_item)
            .setQuery(query, Chat.class)
            .build();

    adapter = new FirebaseListAdapter<Chat>(options) {
        @Override
        protected void populateView(View v, Chat model, int position) {
            //Get reference to the views of list_item.xml
            TextView messageText, messageUser, messageTime;
            messageText = v.findViewById(R.id.message_text);
            messageUser = v.findViewById(R.id.message_user);
            messageTime = v.findViewById(R.id.message_time);

            messageText.setText(model.getMessageText());
            messageUser.setText(model.getMessageUser());
            messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
        }
    };
    listOfMessage.setAdapter(adapter);
}

我的数据库似乎正常,输入没有错误:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

1 个答案:

答案 0 :(得分:0)

您需要获取数据库的参考,然后对其进行查询:

final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

根据您的要求查询类似的内容:-

Query query = reference.child("Chat_room");
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            // dataSnapshot is the "chat_room" node with all children 
            for (DataSnapshot issue : dataSnapshot.getChildren()) {
                // do something with the individual "issues"
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

注意:-确保已创建数据库,将聊天消息保存到数据库的结构对于想要​​检索和显示聊天的方式很重要。