Rgv
Rgv

Reputation: 522

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

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.

Upvotes: 1

Views: 3667

Answers (2)

Vishal Patoliya ツ
Vishal Patoliya ツ

Reputation: 3238

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

            }
        });

Upvotes: 2

Kunu
Kunu

Reputation: 5134

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

Upvotes: 3

Related Questions