Home > Software engineering >  How to store data to Firebase Firestore for current user?
How to store data to Firebase Firestore for current user?

Time:03-30

I'm new toCloud Firestore and currently, I'm working on an android app which is a task management app now I'm working on a task group page I was able to add the task group name to the firebase database but the problem is it is shown to every logged-in user so I want it to be shown to the user which added the task group name, below I added the code of AddTaskGroup activity please share the code by which the data which the task added by the user only shown to him.

AddTaskGroup.java


package com.example.todoappwil;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;

public class AddTaskGroup extends AppCompatActivity {

    private EditText taskGroupNameEdt;
    private Button saveTaskGroupBtn;
    private FirebaseUser firebaseUser;
    private FirebaseAuth firebaseAuth;
    private FirebaseFirestore firebaseFirestore;
    private String userID;
    private String tskGroupName;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_settings);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        final Drawable upArrow = getResources().getDrawable(R.drawable.arrow);
//        upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
//        getSupportActionBar().setHomeAsUpIndicator(upArrow);

        ActionBar actionBar;
        actionBar = getSupportActionBar();

        ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#3498DB"));
        actionBar.setBackgroundDrawable(colorDrawable);

        actionBar.setTitle(Html.fromHtml("<font color='#ffffff'>Add Task Group </font>"));

        taskGroupNameEdt = findViewById(R.id.addtskGrpInput);
        saveTaskGroupBtn = findViewById(R.id.saveTskGroupBtn);

        saveTaskGroupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tskGroupName = taskGroupNameEdt.getText().toString();

                if (TextUtils.isEmpty(tskGroupName)) {
                    taskGroupNameEdt.setError("Enter Task Group");
                }
                else {
                    addTaskDatatoFirestore(tskGroupName);
                }
            }
        });


        userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
        firebaseFirestore = FirebaseFirestore.getInstance();

    }

    private void addTaskDatatoFirestore(String tskGroupName) {
        CollectionReference taskGroups =
                firebaseFirestore.collection("TaskGroups");

        TaskGroupContainer taskGroupContainer = new TaskGroupContainer(tskGroupName);

        taskGroups.add(taskGroupContainer).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Toast.makeText(AddTaskGroup.this, "Task Group Added Successfully",
                        Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(AddTaskGroup.this, "Fail to add Task Group \n"   e,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(AddTaskGroup.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }


}

CodePudding user response:

When you are using the following reference:

CollectionReference taskGroups =
            firebaseFirestore.collection("TaskGroups");

It means that you are trying to add documents under the TaskGroups collection no matter who the user is. If you need to distinguish the documents by who adds them, then you have to add something particular to each object, so it can be distinguished. The simplest solution would be to use Firebase Authentication and add the ID of the user like this:

Firestore-root
   |
   --- TaskGroups (collection)
         |
         --- taskId (document)
              |
              --- tskGroupName: "The best group"
              |
              --- uid: "veryLongId"            
  • Related