Android BitmapFactory 没有从 AsyncTask onPostExecute 上的输入流中获取

标签 android android-asynctask inputstream

我在 doInBackground 中获取输入流文件,然后返回此输入流。这是我的代码

 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 文件,然后返回这个 inputstream, 我设置了

photoImage.setImageBitmap(BitmapFactory.decodeStream(inputStream))

onPostExecute() 但是

BitmapFactory.decodeStream(inputStream) 返回 null

这段代码可能有什么问题?

最佳答案

如果只是将图像加载到 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'

http://square.github.io/picasso/

关于Android BitmapFactory 没有从 AsyncTask onPostExecute 上的输入流中获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41297778/

相关文章:

java - 未弃用的 StringBufferInputStream 等价物

java - 解除阻塞 getInputStream.read(bytes[])

java - 如何在 Google Play 测试/实时中为应用程序设置不同的端点?

Android Studio 布局 dp

android - 状态栏下的 MapView 带有 CollapsingToolbarLayout

java - onPostExecute() 之后新 Intent 未开始

Java:忽略输入流 - 缓冲区会溢出并发生坏事吗?

java - APK 文件写入 SD 卡时损坏

java - 从 AsyncTask 返回位图

android - android中如何决定是否使用ASyncTask?