Paul C
Paul C

Reputation: 27

Iterate Values of a dataSnapshot.value hashmap from a Firebase

I'm creating a "Virtual Garage App" for motorcycles, and I can't retrieve the data from my Firebase, I can only access the HashMap of each motorcycle in database. This is my database content:

database

Here is my code where I try to retrieve the data: code

Here is the ExampleItem() object where I try to place the data: ExampleItem

Is there any way to iterate through the values of the dataSnapshot.value HashMap in order to call the setters for each string?

Upvotes: 1

Views: 633

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Is there any way to iterate through the values of the dataSnapshot.value HashMap in order to call the setters for each string?

You can get it even simpler, by accessing the exact property you need. For example, to display the value of "motoBrand" property, please use the following lines of code:

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

In the exact same way you can get the value of the other properties. In kotlin will look like this:

val rootRef = FirebaseDatabase.getInstance().reference
val mototrackRef = rootRef.child("mototrack")
mototrackRef.get().addOnCompleteListener { task ->
    if (task.isSuccessful) {
        for (ds in task.result.getChildren()) {
            val motoBrand = ds.child("motoBrand").getValue(String::class.java)
            Log.d("TAG", motoBrand)
        }
    } else {
        Log.d("TAG", task.exception.getMessage()) //Don't ignore potential errors!
    }
}

Upvotes: 1

Related Questions