Read a Specific Value from Firebase Database in android - android

I am trying to get a specific value from a firebase database that I have already created. I have followed this youtube tutorial and another similar question which is quite related to what I am trying to achieve.
This is how my Firebase Database looks like Database Tree
I am trying to fetch all the individual items like Name, Snippet, Lat, Long from this db.
Here is what I have tried so far. Right now I have only tried to get Name item
In Oncreate Method :
final TextView nametext = (TextView)findViewById(R.id.name);
Firebase.setAndroidContext(this);
final Firebase ref = new Firebase("https://fir-with-maps.firebaseio.com/Group 2");
final List<PlumbersList> listofplumbers = new ArrayList<>();
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
PlumbersList plumberslist = dataSnapshot.getValue(PlumbersList.class);
listofplumbers.add(plumberslist);
String name = plumberslist.Name;
nametext.setText(name);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
PlumberList class
public class PlumbersList {
String Name;
String Snippet;
String Lat;
String Long;
public PlumbersList() {
}
public PlumbersList(String name, String snippet, String lat, String aLong) {
Name = name;
Snippet = snippet;
Lat = lat;
Long = aLong;
}
public String getName() {
return Name;
}
public String getSnippet() {
return Snippet;
}
public String getLat() {
return Lat;
}
public String getLong() {
return Long;
}
The app crashes after a few seconds. Here is what error logcat looks like
09-09 23:41:19.381 1375-1375/digiart.mapwithfirebase E/UncaughtException: com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
at digiart.mapwithfirebase.checkingfirebase$1.onChildAdded(checkingfirebase.java:36)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:210)
at android.app.ActivityThread.main(ActivityThread.java:5833)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Snippet" (class digiart.mapwithfirebase.PlumbersList), not marked as ignorable (0 known properties: ])
at [Source: java.io.StringReader#297f6a4e; line: 1, column: 13] (through reference chain: digiart.mapwithfirebase.PlumbersList["Snippet"])
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
at digiart.mapwithfirebase.checkingfirebase$1.onChildAdded(checkingfirebase.java:36) 
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48) 
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45) 
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38) 
at android.os.Handler.handleCallback(Handler.java:815) 
at android.os.Handler.dispatchMessage(Handler.java:104) 
at android.os.Looper.loop(Looper.java:210) 
at android.app.ActivityThread.main(ActivityThread.java:5833) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879) 
09-09 23:41:19.711 1375-1375/digiart.mapwithfirebase E/AndroidRuntime: FATAL EXCEPTION: main Process: digiart.mapwithfirebase, PID: 1375
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
at digiart.mapwithfirebase.checkingfirebase$1.onChildAdded(checkingfirebase.java:36)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:210)
at android.app.ActivityThread.main(ActivityThread.java:5833)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Snippet" (class digiart.mapwithfirebase.PlumbersList), not marked as ignorable (0 known properties: ])
at [Source: java.io.StringReader#297f6a4e; line: 1, column: 13] (through reference chain: digiart.mapwithfirebase.PlumbersList["Snippet"])
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
at digiart.mapwithfirebase.checkingfirebase$1.onChildAdded(checkingfirebase.java:36) 
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48) 
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45) 
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38) 
at android.os.Handler.handleCallback(Handler.java:815) 
at android.os.Handler.dispatchMessage(Handler.java:104) 
at android.os.Looper.loop(Looper.java:210) 
at android.app.ActivityThread.main(ActivityThread.java:5833) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879) 
I am new in android coding so I might be making some very silly mistake here.

As per your data tree, you are reading from "Group 2" i.e. you are downloading everything under "Group 2" including the "1". What are you trying to achieve here is the main problem. Will there be data "2", "3", "4" and so on? Are those information required to be retrieved?
NO, I only intened to read information from "1"
- Based on you setting the textview to a single name, I assume you only need the first item. Hence, you should use a addValueEventListener instead, and directly read from https://fir-with-maps.firebaseio.com/Group 2/1
// add child "1"
ref.child("1").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
PlumbersList plumberslist = dataSnapshot.getValue(PlumbersList.class);
}
});
YES, I need everything under "Group 2" - Then you just need to go one level deeper.
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
DataSnapshot childSnapshot = dataSnapshot.getValue(); // get the values of "1"
PlumbersList plumberslist = childSnapshot.getValue(PlumbersList.class);
listofplumbers.add(plumberslist);
String name = plumberslist.Name;
nametext.setText(name);
}
});

Suggestion/Question(?) Why is the object called PlumbersList? it looks more like a single Plumber object.
Getting every plumber in node "group 2" (1,2,3....n), your need to iterate over all the child at that node
ArrayList<Plumber> mPlumbersList = new ArrayList<>();
ref = FirebaseDatabase.getInstance().getReference().child("group 2");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot data : dataSnapshot.getChildren())
{
Plumber plumber = data.getValue(Plumber.class);
mPlumbersList.add(plumber);
}
// Notify the adapter after the foreach loop ends, if this list is backing one
mAdapter.notifyDataSetChanged();
}
...
});

Related

firestore make crash in android

Fatal Exception: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
at com.drriyadh.lab.ui.activity.OrdersActivity$1.onEvent(OrdersActivity.java:112)
at com.drriyadh.lab.ui.activity.OrdersActivity$1.onEvent(OrdersActivity.java:95)
at com.google.firebase.firestore.Query.lambda$addSnapshotListenerInternal$2(Query.java:1133)
at com.google.firebase.firestore.Query$$Lambda$3.onEvent(:6)
at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0(AsyncEventListener.java:42)
at com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run(:6)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8019)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
Hi guys, i added "addSnapshotListener" i did not using any long in my database or anything like this and i getted this crash
my code:
private void getData() {
orderColRef = FirebaseFirestore.getInstance().collection(XXXXX.XXXXXX);
listenerRegistration = orderColRef.whereEqualTo("XXXXXXX", user.getUid()).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
binding.progressBar.setVisibility(View.GONE);
if (error != null) {
Log.d(TAG, "onEvent: " + error.getMessage());
Utils.showErrorMessage(getString(R.string.XXXX), activity);
return;
}
orders.clear();
for (DocumentSnapshot ds : value) {
HomeOrder order = ds.toObject(HomeOrder.class);
order.setAccepted(ds.getBoolean("XXXXXXXX"));
homeOrders.add(order);
}
adapter.notifyDataSetChanged();
}
});
}
private void prepareRecyclerView() {
binding.rvOrders.setHasFixedSize(true);
adapter = new OrdersAdapter(homeOrders, context);
}
this is everything from line 95 to 112
my firestore database did not have any long
and in the model class i just have one int
but this is crash did not show all the time
some time it gone and some time it back
but i did not did any change in this time
Numbers in Firestore are usually interpreted as Long when converting them to Java. So you should change the Integer you have in your HomeOrder class to a Long to ensure the Firestore mapping code can set it correctly.

DatabaseException: Can't convert object of type java.lang.String to type, where has problem?

I want to get the values from firebase, but I get this error, where is the problem?
private RecyclerView recyclerView;
private CamperSiteAdapter camperSiteAdapter;
private List<CamperSiteModel> camperSiteModel;
EditText seatch_bar;
private void readCampSite(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Campsite");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(seatch_bar.getText().toString().equals("")){
camperSiteModel.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
CamperSiteModel camperSiteModel1 = snapshot.getValue(CamperSiteModel.class);
camperSiteModel.add(camperSiteModel1);
}
camperSiteAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
this is model code
public CamperSiteModel() {
}
public CamperSiteModel(String camperSiteID, String camperSiteName, String camperSiteImage, String camperSiteType, String camperSiteDistance, String camperSiteInfo, String camperSiteSummary, String camperSiteAddress, String camperSiteLatitude, String camperSiteLongitude, String camperSitePrice1, String camperSitePrice2, String camperSiteEmail, String camperSiteSub) {
CamperSiteID = camperSiteID;
CamperSiteName = camperSiteName;
CamperSiteImage = camperSiteImage;
CamperSiteType = camperSiteType;
CamperSiteDistance = camperSiteDistance;
CamperSiteInfo = camperSiteInfo;
CamperSiteSummary = camperSiteSummary;
CamperSiteAddress = camperSiteAddress;
CamperSiteLatitude = camperSiteLatitude;
CamperSiteLongitude = camperSiteLongitude;
CamperSitePrice1 = camperSitePrice1;
CamperSitePrice2 = camperSitePrice2;
CamperSiteEmail = camperSiteEmail;
CamperSiteSub = camperSiteSub;
}
this is the firebase database
Campsite
CamperSiteAddress: "90 Tasman Hwy, Orford TAS 7190"
CamperSiteDistance: ""
CamperSiteEmail: ""
CamperSiteImage: "https://media-cdn.tripadvisor.com/media/photo-s..."
CamperSiteInfo: "Raspins Beach"
CamperSiteLatitude: ""
CamperSiteLongitude: ""
CamperSiteName: "Raspins Beach"
CamperSitePrice1: "free"
CamperSitePrice2: "free"
CamperSiteSub: "TAS"
CamperSiteSummary: "Raspins Beach"
CamperSiteType: "Camp"
I don't know why this line was an error.
have I missed something? or where is the error?
is the model problem? or somewhere?
CamperSiteModel camperSiteModel1 = snapshot.getValue(CamperSiteModel.class);
error log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.luvtas.campingau, PID: 11763
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.luvtas.campingau.Model.CamperSiteModel
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.luvtas.campingau.Fragment.ExploreFragment$3.onDataChange(ExploreFragment.java:128)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Remove the for loop, since when you are looping you are retrieving the values of type String and not of the model class:
if(seatch_bar.getText().toString().equals("")){
camperSiteModel.clear();
CamperSiteModel camperSiteModel1 = dataSnapshot.getValue(CamperSiteModel.class);
camperSiteModel.add(camperSiteModel1);
camperSiteAdapter.notifyDataSetChanged();
}
Also in your database add a push id after the node Campsite, and you need to follow the javabean convention
The class properties must be accessible using get, set, is (can be used for boolean properties instead of get), to and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.
You need to follow the camelCase naming convention to be able to map the database fields to the model class.

How to retrieve data from fire base to android text view?

I'm working on a iot project and I want to transfer data from firebase to my android app's textview help me out guys!!
This is my code
code
Firebase JSON
{
"Water_level" : 10,
"valve_1" : 0,
"valve_2" : 0
}
This is my logcat error
10-07 13:49:26.433 25077-25077/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.blogspot.techyfruit360.watercontroller, PID: 25077
com.google.firebase.database.DatabaseException: Failed to convert value of type java.lang.Long to String
at com.google.android.gms.internal.zzelw.zzb(Unknown Source:663)
at com.google.android.gms.internal.zzelw.zza(Unknown Source:0)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source:10)
at com.blogspot.techyfruit360.watercontroller.Main2Activity$1.onDataChange(Main2Activity.java:40)
at com.google.android.gms.internal.zzegf.zza(Unknown Source:13)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source:2)
at com.google.android.gms.internal.zzeig.run(Unknown Source:65)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6518)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
in onDataChange delete everything you have written an try the following
myRef.addListenerForSingleValueEvent( new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exists()){
Map<String, Object> objectMap = (HashMap<String, Object>) dataSnapshot.getValue();
String value = (String) objectMap.get( "Water_level" );
Log.d("Water_level", "Value is: " + value);
textView.setText(value);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
} );
This should solve your issue. Make sure your Database ref is set correctly.
Failed to convert value of type java.lang.Long to String
Inside your onDataChange(),
String value = datasnapshot.getValue(String.class)
It's converting a long value to String that's why you're getting the error.
Try this instead:
String waterLevel = dataSnapshot.child("Water_level").getValue(String.class);
textView.setText(waterLevel)
Or just use toString().

Firebase unable to retrieve value to class

I have a working line of code retrieving each single data, but failed to apply them all to a class. This line is working perfectly.
double value = (double) ds.child("player1score").getValue();
But when it comes to this, it fails and crashes.
int value = (int) ds.child("point").getValue();
Solved this problem by changing it into:
long value = (long ) ds.child("point").getValue();
Yet, when retrieving using class, error occurs.
Here are the whole picture of my codes, appreciate so much for any advice, thanks!!
Round().class
public class Round {
public double player1score;
public double player2score;
public double player3score;
public double player4score;
public int point;
//Constructor
public Round(double player1score, double player2score, double player3score, double player4score, int point) {
this.player1score = player1score;
this.player2score = player2score;
this.player3score = player3score;
this.player4score = player4score;
this.point = point;
//Below are All the getter and setter etc
}
My MainActivity.class.onCreate()
//Declare Variables
UserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference gameInfoRef = rootRef.child("user").child(UserId).child("gameInfo");
DatabaseReference gameRecordRef = rootRef.child("user").child(UserId).child("gameRecord");
String gameKey = "-LLyXhetqj9mj5fgh9bn";
Under onCreate():
gameRecordRef.child(gameKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ListView lv_history = (ListView) findViewById(R.id.lv_history);
//It shows proper results in logcat
System.out.println(ds.getValue());
ArrayList<Round> ResultList = new ArrayList<>();
Round round = (Round) ds.getValue(Round.class);
ResultList.add(round);
ivd_HistoryAdapter adapter = new ivd_HistoryAdapter(id_History.this, ResultList);
lv_history.setAdapter(adapter);
}
}
Firebase structure in text:
"user":
"5xGKRXeHgThQy70lduPEp3mosTj1":
"gameRecord":
"-LLyXhetqj9mj5fgh9bn":
"player1score": 0.5,
"player2score": 0.5,
"player3score": 0.5,
"player4score": 0.5,
"point": 5
Logcat Error: (Edited, not causing by integer type error)
com.google.firebase.database.DatabaseException: Class viwil.mahjongcal.Round does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
at com.google.android.gms.internal.zzelx.zze(Unknown Source)
at com.google.android.gms.internal.zzelw.zzb(Unknown Source)
at com.google.android.gms.internal.zzelw.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at viwil.mahjongcal.id_History$1.onDataChange(id_History.java:51)
at com.google.android.gms.internal.zzegf.zza(Unknown Source)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source)
at com.google.android.gms.internal.zzeig.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Error pointed to this line: (id_History.java:51)
Round round = ds.getValue(Round.class);
Firebase screenshot:
To solve this, please change the following line of code:
int value = (int) ds.child("point").getValue();
to
long score = ds.child("point").getValue(Long.class);
You need to cast that object to an object of type Long and not to a primitive int. Even if you are defining your score property in your model class as an int, in the database that property is stored as a long. By default, the numbers are stored in the Firebase Realtime Database as long numbers and not as ints.

Import Firebase data into android class [duplicate]

This question already has answers here:
Why do I get "Failed to bounce to type" when I turn JSON from Firebase into Java objects?
(3 answers)
Closed 6 years ago.
I'm trying to Query Firebase data and store it into the Dinosaur class from the example link below. I have an issue when importing directly from Firebase into the Dinosaur Facts class. It's able to create the Query and enters the "onChildAdded" method. It then goes to the Dinosaur constructor class but crashes right after that.
DinosaurFacts facts = snapshot.getValue(DinosaurFacts.class); //CRASHES HERE
https://www.firebase.com/docs/android/guide/retrieving-data.html
Here is DinosaurFacts class
package jobsme.com.firebasequery;
import android.util.Log;
public class DinosaurFacts {
long height;
double length;
long weight;
public DinosaurFacts() {
Log.i("MyActivity", "FIIIIIIIIIIIIIIIIIINDMEEEE2");
// empty default constructor, necessary for Firebase to be able to deserialize blog posts
}
public long getHeight() {
Log.i("MyActivity", "FIIIIIIIIIIIIIIIIIINDMEEEE3");
return height;
}
public double getLength() {
return length;
}
public long getWeight() {
return weight;
}
}
Here is the onCreate method in the MainAcitivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
Query queryRef = ref.orderByChild("height");
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
Log.i("MyActivity", "onChildAdded");
DinosaurFacts facts = snapshot.getValue(DinosaurFacts.class);
Log.i("MyActivity", snapshot.getKey() + " was " + facts.getHeight() + " meters tall");
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
// ....
});
Log.i("MyActivity", "FIIIIIIIIIIIIIIIIIINDMEEEE");
}
The query is successful but the importing crashes. Hopefully that means I setup everything correctly?
Here's the log output:
12-11 16:48:37.793 5581-5581/jobsme.com.firebasequery E/AndroidRuntime: FATAL EXCEPTION: main
Process: jobsme.com.firebasequery, PID: 5581
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:196)
at jobsme.com.firebasequery.MainActivity$2.onChildAdded(MainActivity.java:45)
at com.firebase.client.core.ChildEventRegistration$1.run(ChildEventRegistration.java:50)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:37)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "vanished" (class jobsme.com.firebasequery.DinosaurFacts), not marked as ignorable (3 known properties: , "weight", "length", "height"])
at [Source: java.io.StringReader#52851428; line: 1, column: 33] (through reference chain: jobsme.com.firebasequery.DinosaurFacts["vanished"])
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:192)
at jobsme.com.firebasequery.MainActivity$2.onChildAdded(MainActivity.java:45) 
at com.firebase.client.core.ChildEventRegistration$1.run(ChildEventRegistration.java:50) 
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:37) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5001) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
at dalvik.system.NativeStart.main(Native Method) 
This is the JSON for one of the dinosaurs in that database:
"bruhathkayosaurus": {
"appeared": -70000000,
"height": 25,
"length": 44,
"order": "saurischia",
"vanished": -70000000,
"weight": 135000
},
The DinosaurFacts class you're using only has fields+getters for these properties: height, length, weight. So when the Firebase tries to deserialize the JSON into a DinosaurFacts object, it complains about the unmapped properties.
The simplest way to get rid of the error is by telling Jackson (which Firebase uses internally to map between JSON and Java) to ignore any unmapped properties it encounters in the JSON:
#JsonIgnoreProperties(ignoreUnknown = true)
public static class DinosaurFacts {
But be careful with this. If you now write a DinosaurFacts object back into the database, it will only have height, length and weight properties. It will not have: appeared, order or vanished. In fact: even if the properties did exist in the database before, writing this object back will delete them.
So the proper solution is to map all the properties from the JSON structure into the Java class:
public static class DinosaurFacts {
long appeared, vanished;
double height, length, weight;
String order;
public long getAppeared() {
return appeared;
}
public long getVanished() {
return vanished;
}
public double getHeight() {
return height;
}
public double getLength() {
return length;
}
public double getWeight() {
return weight;
}
public String getOrder() {
return order;
}
}

Categories

Resources