How to retrieve the data from Firebase database using REST APIs in android?

点点圈 提交于 2019-12-24 06:27:06

问题


First time i am working with fire base,when am trying to retrieve the data using fire base rest apis i get the response like this,

{
  "-JQjT7REctmFfOAoGI6d" : {
    "age" : "23",
    "name" : "xxx",
    "id" : "1"
  },
  "-JQjT7RGTUdl1FTrjed6" : {
     "age" : "34",
    "name" : "xxx",
    "id" : "1"
  }
}

it contain multiple json objects with diffrent ids without jsonarray.i want to store this data in objects.


回答1:


If you are having problem in parsing just because of keys then you can use a iterator and extract the keys and parse them

if(jObj != null){
    Iterator<Object> keys = jObj.keys();
    while(keys.hasNext()){
        String key = String.valueOf(keys.next()); // this will be your JsonObject key
        JSONObject childObj = jObj.getJSONObject(key);
        if(childObj != null){
             //Parse the data inside your JSONObject
        }
    }
}



回答2:


you can access data by mainly 3 ways
1 addValueEventListener
2 addChildEventListener
3 addListenerForSingleValueEvent

Step 1: Create Model Class

public class UserModel {

    String id;
    String name;
    String age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

Step 2: Access Data In Activity

 Firebase firebaseUserDataReference = new Firebase("your firebase url").child("your root name/");

firebaseUserDataReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Log.d("Call", String.valueOf(dataSnapshot.getValue()));
                for (DataSnapshot postData : dataSnapshot.getChildren()) {
                    UserModel userModel= postData.getValue(UserModel.class);
                    yourArrayList.add(userModel);
                }             
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });


来源:https://stackoverflow.com/questions/38670957/how-to-retrieve-the-data-from-firebase-database-using-rest-apis-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!