我有一个聊天屏幕,它有Firebase数据库支持聊天消息。我可以将消息发布到屏幕和数据库,但问题出现在我离开聊天并返回聊天屏幕时。
聊天屏幕变空,我想从Firebase数据库加载之前的所有聊天。所以我创建了一个带聊天节点的Firebase引用,但无法让用户聊天,因为onCreate中的onDataChange
永远不会被调用。
这是我的聊天屏幕课程
public class Chat_Screen extends AppCompatActivity implements View.OnClickListener,ChildEventListener{
public static final String TAG = "###CHAT SCREEN###";
private EditText TypedMsg;
private ImageButton SendButton,Emo_Button;
String UserName_Intent,UserImage_Intent,UserID_Intent,Room_Name_Intent;
String Chat_Msg,Chat_UserName;
RecyclerView.Adapter adapter;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
Iterator iterator;
Toolbar toolbar;
private ProgressDialog progressDialog;
List<Chat_Wrapper> message=new ArrayList<>();;
DatabaseReference databaseReference;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_screen_main);
TypedMsg= (EditText) findViewById(R.id.Chat_Screen_Text_Message);
SendButton= (ImageButton) findViewById(R.id.Chat_Screen_Send);
Emo_Button= (ImageButton) findViewById(R.id.Chat_Screen_Smiley);
toolbar= (Toolbar) findViewById(R.id.Chat_Screen_Toolbar);
progressDialog=new ProgressDialog(this);
progressDialog.setMessage("This Is Chat Room");
progressDialog.show();
// GET INTENT VALUES FROM USER PROFILE CLASS
UserName_Intent=getIntent().getExtras().getString("Get_Name");
UserImage_Intent=getIntent().getExtras().getString("Get_Image");
UserID_Intent=getIntent().getExtras().getString("Get_Phone");
Room_Name_Intent=getIntent().getExtras().getString("room_user");
// RECYCLER VIEW
recyclerView= (RecyclerView) findViewById(R.id.Chat_Screen_Message_List);
recyclerView.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//FIREBASE FETCH ALL PREVIOUS CHAT OF USERS/CHATROOM ------THIS NEVER CALLS
DatabaseReference db=FirebaseDatabase.getInstance().getReference(Room_Name_Intent);
Log.d(TAG,"Database Reference of child "+db);
db.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Log.d(TAG,"Value of SnapShop is calling");
Log.d(TAG,"Value of SnapShop is calling "+snapshot.getValue());
Log.d(TAG,"Value of SnapShop is calling 2nd "+snapshot.getValue());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.d(TAG,"Value of List "+message+" Value of Adapter "+adapter);
adapter=new Chat_Adapter(this,message);
recyclerView.setAdapter(adapter);
//INITIALIZING MESSAGE ARRAYLIST
SendButton.setOnClickListener(this);
databaseReference= FirebaseDatabase.getInstance().getReference().getRoot().child(Room_Name_Intent);
databaseReference.addChildEventListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.chat_screen_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//HANDLE ITEM SELECTION
switch (item.getItemId()) {
case R.id.sendFile:
Log.d(TAG, "Send File Menu Clicked");
return true;
case R.id.geo:
Log.d(TAG, "Geo Fencing Button Clicked");
return true;
case R.id.Call:
Log.d(TAG, "Call Button Clicked");
Toast.makeText(this, "Call Button Clicked", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onClick(View v) {
int itemClick=v.getId();
switch (itemClick){
case R.id.Chat_Screen_Send:
Log.d(TAG,"Send Button Pressed");
Log.d(TAG,"FireBase Chat Room Level "+databaseReference);
//GET MESSAGE FROM EDIT TEXT INTO HASHMAP TO UPDATE DATABASE
Map<String,Object> map=new HashMap<>();
map.put("Name",UserName_Intent);
map.put("Message",TypedMsg.getText().toString());
String Temp_Key=databaseReference.push().getKey();
Map<String,Object> RoomKey=new HashMap<>();
databaseReference.updateChildren(RoomKey);
DatabaseReference message_Root=databaseReference.child(Temp_Key);
message_Root.updateChildren(map);
Log.d(TAG,"Msg Root "+message_Root);
TypedMsg.setText("");
break;
}
}
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
private void append_chat_conversation(DataSnapshot dataSnapshot){
iterator=dataSnapshot.getChildren().iterator();
while (iterator.hasNext()){
Chat_Msg=(String) ((DataSnapshot)iterator.next()).getValue();
Chat_UserName= (String) ((DataSnapshot)iterator.next()).getValue();
Calendar calendar=Calendar.getInstance(Locale.getDefault());
int hour=calendar.get(Calendar.HOUR_OF_DAY);
int min=calendar.get(Calendar.MINUTE);
int second=calendar.get(Calendar.SECOND);
Log.d(TAG,"Time of the Day "+hour+" -- "+min+" -- "+second);
String time=(hour+" -- "+min+" -- "+second);
Log.d(TAG,Chat_Msg+" TIME "+time+" PHONE "+UserID_Intent+" User Image "+UserImage_Intent+" User Name "+UserName_Intent);
Chat_Wrapper chat_wrapper=new Chat_Wrapper(Chat_Msg,time,UserID_Intent,UserImage_Intent);
message.add(chat_wrapper);
adapter.notifyItemInserted(adapter.getItemCount()+1);
Log.d(TAG,"Chat Msg & User Name "+Chat_Msg+" "+Chat_UserName+" Message List "+message.size());
}
}
}
答案 0 :(得分:0)
使用
获取整个结构mDatabase.child("yourChildId")
然后使用.addListenerForSingleValueEvent
获取您想要的孩子。这会返回对您的引用。将<?php
if (isset($_POST['recherche']))
{
if (empty($_POST['recherche']))
{
exit();
}
//sanitize string entering db
$recherche = filter_input(INPUT_POST, 'recherche', FILTER_SANITIZE_STRING);
$recherche = filter_var($recherche, FILTER_SANITIZE_SPECIAL_CHARS);
//mysqli connection
$mysqli = new mysqli('localhost', 'root', '', 'test');
//statement with FALSE return error handling
if (!$stmt = $mysqli->prepare("SELECT capacityingo FROM smartphone WHERE name = ?"))
{
//throw error
// trigger_error('The statement could not be prepared', E_USER_ERROR);
//or (to be readable by javascript)
$error = array
(
'error' => 'The statement could not be prepared'
);
echo json_encode($error);
exit();
}
$stmt->bind_param('s', $recherche);
//execute with error handling
if (!$stmt->execute())
{
//throw error
// trigger_error('The statement could not be executed', E_USER_ERROR);
//or (to be readable by javascript)
$error = array
(
'error' => 'The statement could not be executed'
);
echo json_encode($error);
exit();
}
//make statement output to result
$res = $stmt->get_result();
$data = array();
while ($row = $res->fetch_assoc())
{
//add each result to an array
$data[] = $row;
//if this does not work try
// array_push ($data, $row);
}
//print the array encoded in JSON
echo json_encode($data);
}
设置为该引用。你尝试过这样的事吗?
答案 1 :(得分:0)
这可能是因为每次你输入调用firebase.updateChildren
的孩子时,它都会删除所有以前的数据并创建新的节点,你的代码就可以获取所有数据了。只要确保每次进入房间都不会创造新房间