gpt4 book ai didi

java - 通过 Firestore 仅存储当前登录用户的数据

转载 作者:行者123 更新时间:2023-11-29 18:46:18 25 4
gpt4 key购买 nike

当我使用用户 account1 登录并上传数据时,让我们说“你好”并获取它,我可以看到“你好”这个词(这就是我想要的)。但是当我注销并使用用户 account2 登录时,每当我单击获取时,它都会显示“你好”。但它不应该显示,因为这是用户 account1 输入的。所以它应该只显示登录用户输入的数据。

如何更改我的代码以允许数据仅由当前登录的用户存储和检索?

下面是代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(this);
setContentView(R.layout.activity_ichild);

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference uidRef = rootRef.collection("RootCollection").document(uid);
POJO pojo = new POJO();
uidRef.set(pojo);


fetch=findViewById(R.id.fetchDocument);


firestore = FirebaseFirestore.getInstance();

upload =findViewById(R.id.uploadText);

upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

POJO pojo = new POJO();
pojo.setValue("Hello World");

//below code creates collection, creates a inner doc. and uploads the value (pojo)

firestore.collection("RootCollection").document("MyDoc")
.set(pojo).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {


//gets called if upload is successful
Toast.makeText(ichild.this,"Upload is successful", Toast.LENGTH_SHORT).show();

}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(ichild.this,"Upload is not successful" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});

}
});

最佳答案

因为每次您都将数据加载到同一个文档中

firestore.collection("RootCollection").document("MyDoc")

相反,您可以使用在路径中引用 id 的文档,所以使用这个

uidRef.set(pojo).addOnSuccessListener(new OnSuccessListener<Void>() {

代替

firestore.collection("RootCollection").document("MyDoc")
.set(pojo).addOnSuccessListener(new OnSuccessListener<Void>() {

并删除它,只设置空对象

POJO pojo = new POJO();
uidRef.set(pojo);

关于java - 通过 Firestore 仅存储当前登录用户的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51751415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com