我有这个简单的程序,它从URL检索图像-----保存在位图上---显示为图像视图。但是,当我尝试运行它时,它总是崩溃。我有downloadBitmap方法将URL转换为位图,然后将图像设置为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;
}
}
问题是
temp.setImageBitmap(image);
在背景内部Thread
。由于我们Thread
除了无法更新UI元素以外,都无法更新UI元素,因此UI Thread
我们需要在完成下载线程后发布回调,或使用AsyncTask
具有进行后台工作的方法和在上进行工作的方法的UI Thread
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句