简体   繁体   中英

Android retrieve the data from Firebase and save it in ArrayList

The Firebase Realtime Database

I have a rating list in the firebase. The child node of the rating list is the username and then followed by the place name and rating. I would like to save the place name and rating data in a different array lists.

Question:

  1. How can I retrieve the data by skipping the user name?
  2. In the array list how can I save the data like this

the place name array ['Bricks Diner', 'Kingstreet Café', 'Royce Hotel'], [AV Rani Supermart Sdn Bhd, FamilyMart Plaza Sentral..]

the rating array [3, 1.5, 3.5], [5, 1.5]...

To achieve that, please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ratingRef = rootRef.child("Rating");
    ratingRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot userSnapshot : task.getResult().getChildren()) {
                List<String> places = new ArrayList<>();
                List<Double> ratings = new ArrayList<>();
                for (DataSnapshot placeSnapshot : userSnapshot.getChildren()) {
                    places.add(placeSnapshot.getKey());
                    ratings.add(placeSnapshot.child("rating").getValue(Double.class));
                }
                Log.d("TAG", places.toString());
                Log.d("TAG", ratings.toString());
            }
        } else {
            Log.d(TAG, task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

The first log statement will print in the logcat:

[Bricks Diner, Kingstreet Café, Royce Hotel]
[AV Rani Supermart Sdn Bhd, FamilyMart Plaza Sentral]
...

The second log statement will print in the logcat:

[3, 1.5, 3.5]
[5, 1.5]
...

Things to notice:

  • To be able to get the data from such a database schema as yours, you need to loop through the DataSnapshot twice using ".getChildren()" method.
  • To have that output, you need two lists, the first is "places" and the second one is "ratings".
  • The name of the place is the key of the node, while the rating is a child within the node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM