firestore make crash in android - 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.

Related

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().

Read a Specific Value from Firebase Database in 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();
}
...
});

Saving to Local Database and Firebase in android

I am developing and Android app and want to save to a local SQLite Database and then want it to sync with Firebase, I have gotten the Firebase sync working I am only having the problem saving to the local database, the app crashes when I click save however the data gets stored in firebase but not in the local SQLite. I have included my code below if anyone can assist.
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating firebase object
Firebase ref = new Firebase(Config.FIREBASE_URL);
ref.keepSynced(true);
//Getting values to store
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
String venue = editVenue.getText().toString().trim();
String DateTime = editDateTime.getText().toString().trim();
//Creating Person object
final MeetingUser person = new MeetingUser();
//Adding values
person.setName(name);
person.setAddress(address);
person.setVenue(venue);
person.setDateTime(DateTime);
//Storing values to firebase
ref.push().setValue(person);
//Write to local SQL database
boolean isInserted = DB.SaveUserMeetings(editTextName.getText().toString(),
editDateTime.getText().toString(),
editVenue.getText().toString(),
editTextAddress.getText().toString());
if (isInserted == true)
Toast.makeText(Capture_Meetings.this, "Data Not Saved", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Capture_Meetings.this, "Data Saved", Toast.LENGTH_SHORT).show();
//Value event listener for realtime data update
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
MeetingUser person = postSnapshot.getValue(MeetingUser.class);
//Adding it to a string
String string = "Name of School: " + person.getName() + "\n Date:" + person.getDateTime() + "\n Venue:" + person.getVenue() + "\nMeeting Notes: " + person.getAddress() + "\n\n";
//Displaying it on textview
textViewPersons.setText(string);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
});
}
My Error log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pooveshin.saica_sgb, PID: 10770
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.pooveshin.saica_sgb.DatabaseHelper.SaveUserMeetings(java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.example.pooveshin.saica_sgb.Capture_Meetings$3.onClick(Capture_Meetings.java:114)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Have you considered using Firebase offline capabilities (https://firebase.google.com/docs/database/android/offline-capabilities) ...enabled by calling following
FirebaseDatabase.getInstance().setPersistenceEnabled(true);

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