Android App Development | Lecture#42 | Hive Learners

𝓖𝓻𝓮𝓮𝓽𝓲𝓷𝓰𝓼

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.

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();

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().

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.

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 -> {

            });


hl_divider.png

Thank You

hl_footer_banner.png



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000