I have this simple program which retrieves an image from a URL ----- saves at bitmap --- displays as image view. However, it keeps on crashes when I try to run it. I have the downloadBitmap method to convert a url into a bitmap and then I want to set image to ImageBitmap?
package com.example.bitmapdisplay;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.fasterxml.jackson.core.JsonParseException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class MainActivity extends Activity {
Bitmap image;
BitmapDrawable bd;
ImageView temp;
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temp = (ImageView) findViewById(R.id.ivImage);
Thread retrieveImage = new Thread() {
public void run(){
try {
image = downloadBitmap("http://i1.cpcache.com/product_zoom/617914535/dickbutt_2_mug.jpg?side=Back&height=250&width=250&padToSquare=true");
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
temp.setImageBitmap(image);
}
}
};
retrieveImage.run();
}
private Bitmap downloadBitmap(String url) throws JsonParseException, IOException{
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
image = BitmapFactory.decodeStream(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
return image;
}
}