我尝试在数据库中写,但是只写发件人和消息。我不明白为什么会这样。我认为问题出在我使用sendMessage的地方。我认为问题是我没有可以为其他用户读取/写入主键。
我在数据库中编写消息的活动。
public class MessageActivity extends AppCompatActivity {
TextView username;
FirebaseUser fuser;
DatabaseReference reference;
Intent intent;
ImageButton btn_send;
EditText text_send;
MessageAdapter messageAdapter;
List<Chat> mchat;
RecyclerView recyclerView;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_message );
btn_send=findViewById ( R.id.btn_send );
text_send=findViewById ( R.id.editText );
recyclerView=findViewById ( R.id.recycler_view1 );
recyclerView.setHasFixedSize ( true );
LinearLayoutManager linearLayoutManager=new LinearLayoutManager ( getApplicationContext () );
linearLayoutManager.setStackFromEnd ( true );
recyclerView.setLayoutManager ( linearLayoutManager );
username=findViewById ( R.id.username6 );
intent=getIntent ();
final String userid=intent.getStringExtra ( "FIRST NAME " );
fuser= FirebaseAuth.getInstance ().getCurrentUser ();
reference= FirebaseDatabase.getInstance ().getReference ("users");
reference.addValueEventListener ( new ValueEventListener () {
@Override
public void onDataChange (@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot:dataSnapshot.getChildren ()){
User user=snapshot.getValue (User.class);
assert user!=null;
assert fuser!=null;
if(!fuser.getUid ().equals ( user.getFirstName () )){
username.setText ( user.getFirstName () );
}
}
readMessages ( fuser.getUid (),userid );
}
@Override
public void onCancelled (@NonNull DatabaseError databaseError) {
}
} );
btn_send.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick (View view) {
String msg=text_send.getText ().toString ();
if(!msg.equals ( "" )){
sendMessage ( fuser.getUid (),msg,userid );
} else{
Toast.makeText ( MessageActivity.this,"You can't send empty",Toast.LENGTH_SHORT ).show ();
}
text_send.setText ( "" );
}
} );
}
private void sendMessage(String sender,String receiver,String message)
{
DatabaseReference reference=FirebaseDatabase.getInstance ().getReference ();
HashMap<String,Object> hashMap=new HashMap<> ( );
hashMap.put ( "sender",sender );
hashMap.put ( "receiver",receiver );
hashMap.put ( "message",message );
reference.child ( "Chats" ).push ().setValue ( hashMap );
}
我希望接收者可以写在数据库中。