我在异步任务中从firebase下载图像,然后将其放在imageview中,直到这里,一切都很好。在onPostExecute()方法中,我想从imageview中获取drawable,我在第一步中放入了image,但由于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());
}
});
}
}
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() {
// ...
}
});
检查onPostExecute()中的图像是否已初始化并引用正确的imageView。