简体   繁体   中英

Get data from firebase realtime database in android

I am trying to get data from firebase realtime database in android. I have created a json data file and imported the json file in firebase database. The data file looks like this :

{
    "data": [
        {
        "name" : "one",
        "age" : "ten"
        },{
        "name" : "two",
        "age" : "twenty"
        }
    ]
}

I have created a POJO class. Now how can I get all the json objects from the array? I've searched for a while but can't understand what will be the reference & child here.

When you said val fireDataBaseRef FirebaseDatabase.getInstance().reference.child("data") you are holding a reference of your root tree. with this reference you can fireDataBaseRef.addChildEventListener(childEventListener)

where

val childEventListener: ChildEventListener = object : ChildEventListener {

        override fun onCancelled(snapshot: DatabaseError?) {}

        override fun onChildMoved(snapshot: DataSnapshot?, p1: String?) {}

        override fun onChildChanged(snapshot: DataSnapshot?, p1: String?) {

        }

        override fun onChildAdded(snapshot: DataSnapshot?, p1: String?) {
            // childs added
        }

        override fun onChildRemoved(snapshot: DataSnapshot?) {

        }
    }

just put some logs in the overrided functions and you will see the action

I would recommend changing your Firebase structure as following:

  • replace [] with {} as Firebase recommends using this practice
  • add a specific unique id for every user(or item) you have in data node.

Take this example:

在此处输入图片说明

As you can see in the picture every user has a specific id. Firebase provides for every user an unique id which you can get with String userId= user.getUid(); .

You can create unique ids aswell and get them using String key = Database.child("users").push().getKey(); (not advised to be used for user ids)

If you wish to read the data you structured I recommend reading this .

Also read this .

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