Muhammad Muzammil
Muhammad Muzammil

Reputation: 1439

Parsing from DataSnapshot to Java class in Firebase using getValue()

I know how to parse a simple DataSnapshot object to any Java class using public T getValue (Class<T> valueType). But after the Firebase 3.0 I am not able to parse the following data to my Java Class, as it contains a custom type instance for which I'm receiving NULL.

NOTE: The same logic was working fine before Firebase 3.0. I suppose its because now Firebase is using GSON instead of JACKSON. Please correct me if I'm wrong

DATA:

{ 
  "address" : "DHA karachi", 
  "addresstitle" : "DHA karachi", 
  "logoimage" : {
    "bucketname" : "test2pwow",
    "id" : "zubairgroup",
    "mediaType" : "image/png",
    "source" : 1,
    "url" : "https://pwowgroupimg.s3.amazonaws.com/zubairgroup1173.png?random=727" 
  },
  "title" : "zubairghori" 
}

Group.java

public class Group {

    public String address;
    public String addresstitle;
    public LogoImage logoimage;

    public Group(){}

}

LogoImage.java

public class LogoImage {

    public String bucketname;
    public String id;

    public LogoImage(){}

}

Code that read:

Group group = datasnapshot.getValue(Group.class); 

It doesn't cast LogoImage part of the database into the logoimage object. We always retrieve null in the logoimage object.

Upvotes: 7

Views: 17685

Answers (4)

Hoa Nguyen
Hoa Nguyen

Reputation: 705

enter image description herepublic T getValue(Class valueType)

1.The class must have a default constructor that takes no arguments

2.The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized

Check it from: this source It'll help you

detail

Upvotes: 12

Jmz
Jmz

Reputation: 169

I had the same problem and solved it by making sure that the arguments of the constructor are spelled the same than the elements saved at Firebase. My mistake was that I was setting the key of Firebase with Uppercase letters and object arguments with lowercase letters.

Upvotes: 1

Sevastyan Savanyuk
Sevastyan Savanyuk

Reputation: 6295

I had the same problem. I solved it by providing not only getters for all the values, but setter too. Hope this helps.

Upvotes: 2

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

I'm not sure why that is causing problem for you. This code works fine for me with the data you provided:

    DatabaseReference ref = database.getReference("37830692");
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Group group = dataSnapshot.getValue(Group.class);
            System.out.println(group);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Screenshot of values showing in the debugger

Upvotes: 10

Related Questions