How to only store data for current logged in user using Firestore

user10198341 :

Below is the code which allows the user to store data into Firestore. The problem is, the uploaded data is viewable for all the users logged into the app. How would I be able to only allow the current user logged in to store the data for their account only?

With Firebase Database I use the following code (which works, but not for Firestore)

FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser(); String userId=user.getUid(); mDatabaseRef = FirebaseDatabase.getInstance().getReference(FB_DATABASE_PATH).child(userId);

The above lines of code allows the data to be stored and retrieved only for the logged in user. So the data is unique to them only.

How can I replicate that for Firestore?

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

        }
    });

    fetch.setOnClickListener(new View.OnClickListener() {
Alex Mamo :

How to only store data for current logged in user using Firestore

You can achieve the same thing if you pass the uid to the document() method. So the following lines of code used in Firebase real-time database:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
mDatabaseRef = FirebaseDatabase.getInstance().getReference(FB_DATABASE_PATH).child(userId);

Is equivalent in Firestore with:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=108521&siteId=1