1

When I log in with user account1 and upload data lets say "Hello" and fetch it, I can see the word "Hello" (which is what I want). But when I log out and log in with user account2 and whenever I click fetch it shows "Hello". But it shouldn't show that, as that was input by user account1. So it should only show data input by the logged in users.

How would I change my code to allow the data only to be stored and retrieved by the current logged in user?

Here is the code below:

@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();
                }
            });

        }
    });
ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
user10198341
  • 55
  • 1
  • 3

1 Answers1

2

Because every time you are loading data to same document

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

instead you can use the document which referring the id in the path,so use this

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

instead of

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

and remove this, just setting empty objects

POJO pojo = new POJO();
uidRef.set(pojo);
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68