我想在下图中获取sender_uid
值:
这是我的以下代码。我没有任何价值,也不知道为什么。有人可以解释代码有什么问题吗?谢谢!
编辑:我只希望每个父母的最后 sender_uid -例如:
391rfBEXjVUplEW8aoahMtluSmz1_6dTv7oHnWOh55XzRuf9ouZFZkGt2
的
我只需要 LJxvDjdetWz1-DAFVCy 中的 sender_uid , LJxvA65WA7MX8aaX5nF 中的否。
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<UsersListGetter> usersList = new ArrayList<>();
recyclerView.setAdapter(new UsersListAdapter(usersList, getApplicationContext()));
recyclerView.setAdapter(new UsersListAdapter(null, getApplicationContext()));
for (DataSnapshot ch : dataSnapshot.getChildren()) {
String senderReceiver[] = ch.getKey().split("_");
if (senderReceiver[0].equals(mAuth.getUid()) || senderReceiver[1].equals(mAuth.getUid())) {
Query lastQuery = mDatabase.child(ch.getKey()).orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message_body").getValue().toString();
Log.d("MSG", message);
}
@Override
public void onCancelled(DatabaseError databaseError) {
//Handle possible errors.
}
});
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
答案 0 :(得分:1)
您可以通过这种方式从每个节点获取sender_uid
首先创建一个pojo类以获取所需数据
public class UserPojo {
private String sender_uid;
public UserPojo() {
}
public String getSender_uid() {
return sender_uid;
}
public void setSender_uid(String sender_uid) {
this.sender_uid = sender_uid;
}
}
,然后为每个聊天参考取回它
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<UsersListGetter> usersList = new ArrayList<>();
recyclerView.setAdapter(new UsersListAdapter(usersList, getApplicationContext()));
recyclerView.setAdapter(new UsersListAdapter(null, getApplicationContext()));
for (DataSnapshot ch : dataSnapshot.getChildren()) {
UserPojo up = ch.getValue(UserPojo.class);
String senderUid = up.getSender_uid(); //here you got your sender_uid
Query lastQuery = mDatabase.child(ch.getKey()).orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message_body").getValue().toString();
Log.d("MSG", message);
}
@Override
public void onCancelled(DatabaseError databaseError) {
//Handle possible errors.
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
答案 1 :(得分:0)
假设chat
节点是Firebase根目录的直接子节点,要解决此问题,请使用以下查询:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef
.child("chat")
.child(receiver_id + "_" + sender_uid)
.orderByChild("sender_uid")
.limitToLast(1);
query.addListenerForSingleValueEvent(/* ... */);