Reputation: 55
I'm using addChildEventListener
for my chat application
Query chatRoot = Qref
.child("Messages")
.orderByChild("lobbykey")
.equalTo(lobbykey);`
This is the query that I am using works fine to my knowledge, just a bit of idea on what I'm trying to do. I also have a constructor class for my list to place objects:
public ChatParameters(String userUID, String message, String imageURL, String sender, String lobbykey, String msgkey) {
this.UserUID = userUID;
this.sender = sender;
this.message = message;
this.imageURL = imageURL;
this.lobbykey = lobbykey;
this.msgkey = msgkey;
}
The onchildadded listener works fine. When I tried it with just Toast, it make text works fine. But when i add the Chatparameters.class to get all the values it crashes
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot chatSnapshot: dataSnapshot.getChildren()){
ChatParameters chatParameters = chat.getValue(ChatParameters.class); //i get the error here.
}
}
this is the error logcat, it's refering to ChatParameters chatParameters = chat.getValue(ChatParameters.class);
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.woofy_nocco.testapp.ChatParameters
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 com.example.woofy_nocco.testapp.Chatroom$1.onChildAdded(Chatroom.java:78)
at com.google.android.gms.internal.zzecw.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:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
this is what my database structure looks like
Upvotes: 1
Views: 188
Reputation: 598728
The onChildAdded
method of your ChildEventListener
is invoked on individual child nodes already. So most likely you don't need to loop over dataSnapshot.getChildren()
in there:
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ChatParameters chatParameters = dataSnapshot.getValue(ChatParameters.class);
}
Explanation of the problem:
By looping over dataSnapshot.getChildren()
the chatSnapshot
will end up referring to individual properties of the chat message. So if your ChatParameters
consists if a text
property and a message
property, the chatSnapshot
will be point to that text
or message
property, and chatSnapshot.getValue()
will be a string. Since a String
can't be converted to your ChatParameters
class, the SDK throws an exception.
Upvotes: 1