Kemo Kemo - 3 months ago 20
Java Question

Displaying default image if there is no image on server in Android

I am learning Android by working through some tutorials. I am currently working on this tutorial from androidhive. The goal of this tutorial is to display a list of movies and display year, genre, image... So now I have a question, what happens when there is no image on the server.

movie.setThumbnailUrl(obj.getString("image"));


XML:

<com.android.volley.toolbox.NetworkImageView
android:id="@+id/thumbnail"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp" />


How would I display a default image (for example from drawable) if the image does not exist on the server?

Answer

Just add a default background to the networkImageView in xml :

<com.android.volley.toolbox.NetworkImageView
    android:id="@+id/thumbnail"
    android:background:"@drawable/default_image"
    ... />

and check if is string null or empty

if (obj.getString("image") != null && !obj.getString("image").isEmpty()) {
     movie.setThumbnailUrl(obj.getString("image"));
}

and if you want to set it programatically just use else :

else {
   movie.setDefaultImageResId(R.drawable.default);
   movie.setErrorImageResId(R.drawable.error);
}
Comments