0
votes

I have implemented an authentication process using Firebase, my user should now be able to add data and have it displayed on a user-specific scale (each user has their own data).

From what I have read, this is how I can add data to the Database:

 private void setData() {
    // Write a message to the database
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("Message");

    myRef.setValue("Hello World !");
}

But in the console, the data seems to be accessible by all users, is the Firebase database what I should use in order to store user-specific data? If so, how may that be achieved?

Excuse me if my question is obvious, but I am rather new to these principles.

1

1 Answers

2
votes

Create a unique identifier for each user, and host the data for each user under that unique identifier. The unique id can be created using whatever method you like such as the UDID of the device or by simply getting the firebase uid of the authenticated user. For example the following may work if you want to access a uid without Firebase.

private void setData() {
  String uniqueId = java.util.UUID;
  FirebaseDatabase database = FirebaseDatabase.getInstance();
  DatabaseReference myRef = database.getReference("Message");
  myRef.child(uniqueId).setValue("Hello World !");
}

However, using the uid generated through Firebase authentication is recommended. Where the first example breaks down is if the same user logs on to two different devices using the same account, which would prevent them from accessing their own data from the original device as each device would have different uuids. On the other hand, the Firebase uid would be the same on each device, and so the same user on both devices would have access to the same data. If you want to access the firebase uid (recommended):

private void setData() {
  FirebaseUser user = firebaseAuth.getCurrentUser();
  String uniqueId = user.getUid()
  FirebaseDatabase database = FirebaseDatabase.getInstance();
  DatabaseReference myRef = database.getReference("Message");
  myRef.child(uniqueId).setValue("Hello World !");
}