Check if the image file exists on Server (Android)

advertisements

I have a file directory on my server with images. The name of the image is associated with an items table. Item ID#1, will have a corresponding image "1.png".

Not all items have an image so if the app checks, it will find nothing on some of them. In that case, I want an if check to show a default image.

My question: with only a URL available, how can I check if the url leads to an image or if it leads to nothing/blank/null?


I would suggest asking for the Head of the image request simply because it is faster.

Non Picasso :

HttpClient client= new DefaultHttpClient();
HttpHead headMethod = new HttpHead(urlToImage);
HttpResponse response = client.execute(headMethod);
if(response.getStatusLine().getStatusCode== HttpStatus.SC_NOT_FOUND) {
    // Image does not exist, show a placeholder or something
} else {
  // load image into the view.
}

Picasso : (nothing to do with the head version, but this is an easy alternative to handle it, also look at the Callback that Picasso can take in to fine tune the success/error)

Picasso.with(context).load(urlToImage).into(imageView).placeholder(R.drawable.user_placeholder).error(R.drawable.user_placeholder_error);

References:

Apache HttpHead from Android's SDK Reference

Apache HttpStatus from Android's SDK Reference

Square Picasso