2

I've put together a very simple android app to get used to using firebase on android. Following the getting started part of Firebase's docs I am able to write to the database with no issue. But when I go to retrieve that data with getValue from the database, the app crashes.

I try to read the database with the following code:

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");

ValueEventListener chatMessageListener = new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    TextView messages = (TextView) findViewById(R.id.old_messages);
    chatMessage ChatMessage = dataSnapshot.getValue(chatMessage.class);
    String message = dataSnapshot.toString();
  }

  @Override
  public void onCancelled(DatabaseError error) { 
    //.... 
  }
 };
myRef.addValueEventListener(chatMessageListener);

The JSON is very simple: this is taken from firebase, this data was provided from the app

I've also created "chatMessage" that was used for the writing the data:

@IgnoreExtraProperties
private static class chatMessage {
  public String message;
  public String messageFrom;
  public String messageTo;

  public chatMessage() {  }

  public chatMessage(String message, String messageFrom, String messageTo) {
    this.message = message;
    this.messageFrom = messageFrom;
    this.messageTo = messageTo;
  }

  public String getMessage(){
    return message;
  }

  public String getMessageFrom(){
    return messageFrom;
  }

  public String getMessageTo(){
    return messageTo;
  }
}
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96

3 Answers3

3

I see some issues with your code.

First your chatMessage class was not written in the java patterns. Every class name must start with an upper case letter.

private static class ChatMessage {

Your two constructors must also start with a capital letter

public ChatMessage() {  }

And in your onDataChange

ChatMessage chatMessage = dataSnapshot.getValue(ChatMessage.class);

also, you should be getting your message string using your ChatMessage object

String message = chatMessage.getMessage();
adolfosrs
  • 9,286
  • 5
  • 39
  • 67
  • Looks like that was it. The crashing has gone away. It's not putting the text on the screen yet, but it looks like I'm in a way better position than I was. – Richard Peterson Jul 02 '16 at 20:15
-1

Try to stay away from camelCase writing (e.g. "messageFrom"). It seems that Firebase does not like capital letters for the labels

Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40
-1

change object into String using

String message = String.valueOf(dataSnapshot.getvalue());

instead of

String message = dataSnapshot.getvaluse().toString();
Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156