robbert phillop robbert phillop - 1 year ago 54
Android Question

Android: imageURI from firebase database crash

I am building a simple message app, at the moment i would like to view the users image next to their text. Here I am trying to get the users image from the firebase database. However, whenever I try to getValue() of the an image the app seems to crash. If I choose to replace imageURI with an image link, then I see it works with that link.

08-27 23:14:02.392 4817-4817/com.myproj.blogapp E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.myproj.blogapp.MessageAdapter$1.onDataChange(
at Source)
at Source)
at Source)
at android.os.Handler.handleCallback(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(

public void onBindViewHolder(final MessageViewHolder viewHolder, final int index) {

final Message c = messagesList.get(index);

final String sender = c.getFrom();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(sender);
databaseReference.addValueEventListener(new ValueEventListener() {

public void onDataChange(DataSnapshot dataSnapshot) {

imageUrl = dataSnapshot.child("image").getValue().toString(); //error on this line

String name = dataSnapshot.child("name").getValue().toString();

public void onCancelled(DatabaseError databaseError) {



Database Image

Answer Source

Your data is not complete. Look at the rust user. It has no image...

You must either use a proper null check after getChild(String path) before you toString it

Or use hasChild(String path) before getting it at all

In the case where the value is null or the child doesn't exist, you might want to consider having a default image

Note: you could be using getValue(String.class) on the children instead of using toString, or use a POJO on the whole initial Snapshot instead of fetching individual children

You'll also want to implement onCancelled so you can see your Firebase errors

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download