1

How to retrieve all the key nodes and values inside a model class?

Here is my database schema.

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

1 Answers1

0

How to create a model class for dynamic keys?

There's no way you can do that. You cannot have dynamic variable names inside a class. The name of the fields that exist in a class should match the ones the exist in the database. However, there is a way in which you can read dynamic data and that would be:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("MyData").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot ds : task.getResult().getChildren()) {
                String key = ds.getKey();
                String value = ds.getValue(String.class);
                Log.d("TAG", key + "/" + value);
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

This will work assuming that "S71M ... b7z1" is the UID of the authenticated user. If it's not, you have to hardcode that value inside the second .child("S71M ... b7z1") call.

The above code will produce the following result in the logcat:

3/10
13/60
...

Also, remember that you need to have the same type of data for all the values. As I see in your schema, you don't have. Some are strings and others are numbers:

enter image description here

So try to change all values to String, and the code may remain unchanged or, change all values to be numbers and the use:

long value = ds.getValue(Long.class);

In case of keys, there is nothing you should do, as all keys are strings.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • then how to retrive this data on reyclerview according to their respective user – Sourabh Kumar Oct 28 '21 at 08:26
  • It sounds like your question started off about "how to create a model class for dynamic keys and values", but now you are asking how to display the data in a RecyclerView. Here is an example of a [working solution](https://stackoverflow.com/questions/49383687/how-can-i-retrieve-data-from-firebase-to-my-adapter/49384849). At this point, I recommend you make your own attempt to achieve that, and ask another question if something else comes up. In this way, I or other Firebase developers will be able to help you. – Alex Mamo Oct 28 '21 at 08:41