Android App Development | Lecture#42 | Hive Learners

Words
342
Reading
2 min
Listen
Play
4y

饾摉饾摶饾摦饾摦饾摻饾摬饾摲饾摪饾摷

Hello dear members of Hive Learners, yesterday we sent data to firebase using the push method. It auto-generates a string and adds data inside it. What if we need to store the data for every user ID used by the login account? For example, if I log in with [email protected], and Firebase assigns me a permanent id that we can use to call this user or identify the user in a Firebase manner. So let's see how we can save data differently with several parents.

alt

GitHub Link

Use this GitHub project to clone into your directory. The following lecture will constantly update it so you will never miss the latest code. Happy Coding!

What Should I Learn

  • How to store data under Firebase User ID
  • How to update data

Assignment

  • Update Data on Button Click

Procedure

First, we need to get the ID of the login user. We will also set a check if the user is login or not. It will prevent the null exception.

if (firebaseAuth.getCurrentUser() != null) {
                Toast.makeText(this, "Login Session Expired", Toast.LENGTH_SHORT).show();
                return;
            }

            String fid = firebaseAuth.getCurrentUser().getUid();

alt

Now we can remove the push() and replace it with the child(). It becomes the child of the parent reference sendings. We need to provide the child's name in child().

alt

The amount is saved in the database in String form. What if we need to store it in integers of in float value? We need to convert it and save it in the databases by keeping the second parameter of the hashmap to Object.

alt

Now we can update the value as we set User ID as the parent of the hashmap values. We know all the parents. Use the updated children method by using the same database reference and it child Firebase User if fid. This time I am using different HAsjMap values so that we can notice the changes.

Note that setValues can also update the values but if it does not update it overrides the child. If the child is not there it will create a new one. But updating children only adds value to existing children.

hashMap.put("account", "My Account");
            hashMap.put("amount", 1.21);

            sendings_ref.child(fid).updateChildren(hashMap).addOnCompleteListener(task -> {

            });

alt

hl_divider.png

Thank You

hl_footer_banner.png

Android App Development | Lecture#42 | Hive Learners | Ecency