问题描述
我正在做一个项目。我想让每个用户的数据彼此分开。我想我在从 Firebase 实时数据库保存和检索数据时遇到了问题。
我有两张桌子:
-
“用户”
- 用户名、电子邮件、电话、密码
-
“密码”
- 帐户类型、用户名、电子邮件、电话、密码
第一个用户注册并保存各自的密码/数据,然后退出系统。并且当第二个用户注册时,第二个用户将看不到第一个用户的数据。
这里是保存密码/数据
String id = databaseReference.push().getKey();
PasswordModel model = new PasswordModel(accountType,userName,email,phone,password);
assert id != null;
databaseReference.child(id).setValue(model);
Toast.makeText(this,"Data Successfully Saved",Toast.LENGTH_SHORT).show();
textClear();
startActivity(new Intent(MainActivity.this,AllPasswordsActivity.class));
这里我将数据设置为 Recyclerview
public void setData() {
binding.recyclerViewPasswords.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<PasswordModel> options =
new FirebaseRecyclerOptions.Builder<PasswordModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("passwords"),PasswordModel.class)
.build();
adapter = new PasswordAdapter(options);
binding.recyclerViewPasswords.setAdapter(adapter);
}
解决方法
我在保存数据方面做了一些更改
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
userId = firebaseUser.getUid();
final String id = databaseReference.push().getKey(); // AUTO GENERATING ID
final PasswordModel model = new PasswordModel(accountType,userName,email,phone,password);
databaseReference.child(userId).child(id).setValue(model);
Toast.makeText(getApplicationContext(),"Data Successfully Saved",Toast.LENGTH_SHORT).show();
textClear();
startActivity(new Intent(MainActivity.this,AllPasswordsActivity.class));
以及检索数据的一些变化
public void setData() {
binding.recyclerViewPasswords.setLayoutManager(new LinearLayoutManager(this));
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
userId = firebaseUser.getUid();
databaseReference.child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
FirebaseRecyclerOptions<PasswordModel> options =
new FirebaseRecyclerOptions.Builder<PasswordModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("passwords").child(userId),PasswordModel.class)
.build();
adapter = new PasswordAdapter(options);
adapter.startListening();
binding.recyclerViewPasswords.setAdapter(adapter);
} else {
Toast.makeText(AllPasswordsActivity.this,"No data available for this user,Save your data",Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
问题已解决。