【问题标题】:Async Task onPost throws exception异步任务 onPost 引发异常
【发布时间】:2019-04-12 18:44:50
【问题描述】:

我正在异步任务中从 firebase 下载图像,然后将其放在 imageview 中,直到这里,一切都很好。在 onPostExecute() 方法中,我想从我在第一步中放入图像的 imageview 中获取可绘制对象,但它会抛出异常,因为它 imageview 不包含任何内容。

public class DownloadPhoto extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        downloadImage();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
        Palette colorPalette = Palette.from(bitmap).generate();
        int darkVibrantColor = colorPalette.getDarkVibrantColor(Color.parseColor("#546369"));
        title.setTextColor(darkVibrantColor);
        details.setTextColor(darkVibrantColor);
    }

}

我在下载时没有任何问题,它会正确下载并将图像放入 imageview 中。不过,我最好在主处理中下载图像而不是在异步任务中,但不确定是否可以。

下载图片功能

private void downloadProfileImage() {
    downloadImage = new DownloadImage("image_" + id + ".jpg", storageReference);
    downloadImage.download(image);
}

下载类

public class DownloadImage {
private String name;
private StorageReference storageReference;

public DownloadImage(String name, StorageReference storageReference) {
    this.name = name;
    this.storageReference = storageReference;
}

public void download(final ImageView ımageView) {
    StorageReference sRef = storageReference.child("images/" + name);
    sRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            Picasso.get().load(uri).into(ımageView);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.i("resultDownload", e.getLocalizedMessage());
        }
    });
}
}

【问题讨论】:

  • 添加下载图片功能。
  • 新增下载图片功能

标签: java android firebase android-asynctask firebase-storage


【解决方案1】:
Try this code
Picasso mPicasso = Picasso.with(this);
            mPicasso.load(imageUrl)
                    .into(image1, new com.squareup.picasso.Callback() {


            @Override
                    public void onSuccess() {
                        Drawable drawable = image1.getDrawable();

                        // ...
                    }

                    @Override
                    public void onError() {
                        // ...
                    }
                });

【讨论】:

    【解决方案2】:

    检查onPostExecute()中的图片是否已经初始化并引用了正确的imageView。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      相关资源
      最近更新 更多