我在doInBackground
中获取Inputstream文件,然后返回此输入流。这是我的代码
class PhotoAddTask extends AsyncTask<Void, Integer, InputStream> {
public PhotoAddTask(ProgressDialog dialog) {
this.dialog = dialog;
}
@Override
protected void onPreExecute() {
dialog.setMessage("Doing something, please wait.");
dialog.show();
}
@Override
protected InputStream doInBackground(Void... voids) {
InputStream inputStream = null;
try {
String url = "http://some-url"
inputStream = getImageFromURL(url);
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
@Override
protected void onPostExecute(InputStream inputStream) {
if (dialog.isShowing()) {
dialog.dismiss();
}
photoImage.setImageBitmap(BitmapFactory.decodeStream(inputStream));
}
}
public BufferedHttpEntity getImageFromURL(String fileUrl) {
BufferedHttpEntity breader = null;
try {
HttpGet httpRequest = null;
httpRequest = new HttpGet(fileUrl);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
breader = new BufferedHttpEntity(entity);
} catch (IOException e) {
e.printStackTrace();
}
return breader;
问:我在doInBackground中获取Inputstream文件然后返回此输入流, 我设置了
photoImage.setImageBitmap(BitmapFactory.decodeStream(inputStream))
在onPostExecute()
但
BitmapFactory.decodeStream(inputStream)
返回null
。
这段代码有什么问题?
答案 0 :(得分:1)
如果只是将图像加载到imageViews中,我建议您使用Picasso库而不是AsyncTask。
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
String imageURL = "http://IMAGE_URL";
Picasso.with(context)
.load(imageURL)
.into(imageView);
Picasso处理位图内存问题,性能和缓存。
您还需要将库添加到gradle:
compile 'com.squareup.picasso:picasso:2.5.2'
答案 1 :(得分:0)
你能展示方法getImageFromURL()
吗?请避免这种解决方案。如果您想获取照片然后设置ImageView,请使用Glide或Picasso。