这是我第一次编写与Firebase连接的android应用; 我为聊天活动编写了此代码,问题是,当我尝试编写一个味精并发送此味精时,它在实时数据库中未更新 我的实时数据库为空,我不知道该如何添加子级 或将用户添加到我的实时数据库中,请帮助我。
public class users_fragment extends Fragment {
private RecyclerView recyclerView ;
private UserAdapter userAdapter;
private List<User> mUsers ;
private DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();;
DatabaseReference users = mRootRef.child("users");
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_users_fragment, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
readUsers();
return view;
}
private void readUsers(){
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
//DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Users");
users.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
assert user != null;
assert firebaseUser != null;
if (!user.getId().equals(firebaseUser.getUid())){
mUsers.add(user);
}
}
userAdapter = new UserAdapter(getContext() , mUsers);
recyclerView.setAdapter(userAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
答案 0 :(得分:0)
好像您正在尝试从无到有地创建一些东西 码。您正在添加一个尚未在数据库中的用户 尚未添加。现在,引用可以。
添加用户det
userId = datRef.push.getkey(); 用户mUser =新用户(userId,userName); datRef.child(userId).setValue(mUser)
要从数据库中读取数据,现在您可以执行 datRef.addValueEventListener(valueeventlistener)