我正在处理一个项目,在该项目中,我必须将数据从一个活动传递到另一个活动。我尝试使用位图来传递图像。从Firebase存储中检索图像后,我可以用System.out输出它,但如果我试图在fetch方法之外读取它,它会在控制台中返回null。
for (DocumentSnapshot result : Objects.requireNonNull(task.getResult()).getDocuments()
) {
title = Objects.requireNonNull(result.get("Author")).toString();
author = Objects.requireNonNull(result.get("Title")).toString();
edition = Objects.requireNonNull(result.get("Edition")).toString();
isbn = Objects.requireNonNull(result.get("ISBN")).toString();
category = Objects.requireNonNull(result.get("Category")).toString();
reviews = result.get("Reviews");
Bitmap[] bitmap = new Bitmap[1];
try {
final File local_file = File.createTempFile("android_dev", "jpg");
storageRef.getFile(local_file).addOnCompleteListener(bitmap_task -> {
if (bitmap_task.isSuccessful()){
System.out.println("Sucess");
bitmap[0] = BitmapFactory.decodeFile(local_file.getAbsolutePath());
System.out.println(bitmap[0] + " yes yes");
}else {
System.out.println("Failure!");
}
});
} catch (IOException e) {
e.printStackTrace();
}
if (category.equals(finalBook_category)) {
if (title.contains(search) || author.contains(search) || edition.contains(search) || isbn.contains(search)) {
System.out.println(bitmap[0] + "What is happening");
books_list.add(new LibraryBook(author, title, edition, isbn, category, reviews, bitmap[0]));
}
}
}
setAdapter();
} else {
System.out.println("Nope");
}
});
}
你指的是这一行吗
System.out.println(bitmap[0] + "What is happening");
作为您看不到预期位图输出的点?如果是这样,那是因为getFile()
是返回Task
的方法,带有addOnCompleteListener
回调。所以它不是同步的。所以你的代码到达这个部分:
if (category.equals(finalBook_category)) {
if (title.contains(search) || author.contains(search) || edition.contains(search) || isbn.contains(search)) {
System.out.println(bitmap[0] + "What is happening");
books_list.add(new LibraryBook(author, title, edition, isbn, category, reviews, bitmap[0]));
}
}
在从存储桶中提取位图之前。把if语句放在这行下面:
System.out.println(bitmap[0] + " yes yes");
这样它就可以等到回调,并且您知道在使用它之前已经下载了图像