1

I'm trying to save the user details using a date as a unqiue id. I'm displaying the date on top which Ii get from a calendar view on another page.

I'm displaying the date on top which Ii get from a calendar view on another page.

I was wondering if I can use the date as a unique id to save other data inside it, and also use it read it when the time comes.

Currently, to write the data I'm using this code:

String id =databaseWorkouts.push().getKey();
Workout workout = new Workout(id, name, category );
databaseWorkouts.child(id).setValue(workout);

Thanks,

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

1

What I see in your code is that you are using the push() method to generate that random unique key and you then you using it in the reference to add the object of Workout class to the database. You and not using the date as an identifier. Using push() method is a common practice when it comes Firebase. This random generated key provided by the this method is based on time. So, there is no need change this in any way.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

It's pretty easy to push each workout under the date.

String id =databaseWorkouts.push().getKey();
Workout workout = new Workout(id, name, category );
databaseWorkouts.child("2018-02-06").child(id).setValue(workout);

You'll want to calculate the date, so consider this just an example.

But with this data structure, you can only query workouts for a specific date. If you want to query workouts across all dates, this database structure no longer allows it.

As a side note: it is not necessary to store the key in the Workout, since it is already available in the database. To keep the key only once, and still have it available in your Workout object, see Is there a way to store Key in class which I cast from Firebase object?.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807