Mohan Adhikari
Mohan Adhikari

Reputation: 89

Firebase Android - Saving data objects to user ID

I'm trying to save user data on my app under the user Id.

For now, I can save the information based on a "workout" and another one on "workout details". The details is saved under the "workout" id so its connected.

What i'm trying to do is save the data under the unique user id that is created using Google login.

So when a user saves the detail he/she can only see their own detail now. I do have the normal Firebase database rule setup.

private  void addWorkout(){
        String name = editTextName.getText().toString().trim();
        String category = spinnerCategory.getSelectedItem().toString();

        //if name not empty we save it to firebase db
        if(!TextUtils.isEmpty(name)){

            //make it so it saves under the user ID
            FirebaseUser user = firebaseAuth.getCurrentUser();

            //create a unique id for workout to save in firebase

            String id =databaseWorkouts.push().getKey();

            Workout workout = new Workout(id, name, category );

            //set value method to save in firebase db
            databaseWorkouts.child(id).setValue(workout);

            Toast.makeText(this, "Workout added", Toast.LENGTH_LONG).show();
            editTextName.setText("");

Upvotes: 1

Views: 4476

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

To solve this, use instead of using that random generated key provided by the push() method, use the uid from the FirebaseUser object like this:

String id = user.getUid();
Workout workout = new Workout(id, name, category);
databaseWorkouts.child(id).setValue(workout);
Toast.makeText(this, "Workout added", Toast.LENGTH_LONG).show();
editTextName.setText("");

Upvotes: 1

Emmanuel Montt
Emmanuel Montt

Reputation: 376

you need first have the user id and StorageReference from your database

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

if (user == null) {
    // No session user
    return;
}

// In this example is QMvzmlCksCPgFSpuVNxwBuVBvaA2

String userId = user.getUid();

//Example you need save a Store in 
FirebaseDatabase database = FirebaseDatabase.getInstance();

DatabaseReference stores = database.getReference("stores");

stores.child(userId).push().setValue(store);

where store is a class that you need save.

Store store= new Store();

public class Store {

public String url;
public String username;
public String password;
public String image;
public String name;

public Store() {
}

public Store(String url, String username, String password, String image, String name) {
    this.url = url;
    this.username = username;
    this.password = password;
    this.image = image;
    this.name = name;
}

}

Finally you will have in your Firebase Database Example saved store data in Firebase Database

Note: your can omite .push() if you not want a List data

Upvotes: 0

Related Questions