我正在使用来自内部存储的ImageView。流程是:
1)检查内部存储器中的文件名是否已存在 2)如果是,请在ImageView中将其用作Bitmap 3)如果没有,请从URL下载,将Bitmap设置为ImageView,并将Stream复制到内部存储中的文件
实际代码为
try{
InputStream fis = holder.mImageView.getContext().openFileInput("file.png");
tempImageView.setImageBitmap(BitmapFactory.decodeStream(fis));
fileFound = true;
fis.close();
}
catch(IOException e){
try{
FileOutputStream fos = holder.mImageView.getContext().openFileOutput("file.png",Context.MODE_APPEND);
thumbPhotoRef.getStream(
new StreamDownloadTask.StreamProcessor() {
@Override
public void doInBackground(StreamDownloadTask.TaskSnapshot taskSnapshot,
InputStream inputStream) throws IOException {
byte[] buffer = new byte[8192];
int size;
tempImageView.setImageBitmap(BitmapFactory.decodeStream(inputStream));
while ((size = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, size);
}
fos.close();
// Close the stream at the end of the Task
inputStream.close();
}
});
}
catch(IOException e){
}
}
tempImageView是一个全局声明的ImageView处理程序,它引用布局中的ImageView
getStream方法中的逻辑,其中Image Bitmap由以下方式分配: tempImageView.setImageBitmap(BitmapFactory.decodeStream(的inputStream));
这实际上有效,Image在布局中适当更新。请注意,在同一方法中,相同的输入流正被写入指向“file.png”的“fos”FileOutputStream变量。
没有任何错误或包括在调试中的任何错误,但不知何故,下次打开文件时(据说已经写入之前),无法设置ImageView的位图。而且我确定该文件现在已存在,因为openFileInput不会再找到文件未找到Exception。
InputStream fis = holder.mImageView.getContext().openFileInput("file.png");
tempImageView.setImageBitmap(BitmapFactory.decodeStream(fis));
任何想法出了什么问题,或者如何在调试模式下获取变量fis的值,看看它是否实际包含setImageBitmap可以理解的任何Bitmap数据?感谢
答案 0 :(得分:0)
解决了它。
刚刚发现InputStream一旦使用就会被消耗掉。
我的解决方案是再次读取之前由OutputStream写入的InputStream,以便我获得副本:
OutputStream fos = holder.mImageView.getContext().openFileOutput(path,Context.MODE_PRIVATE);
while ((size = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, size);
}
InputStream isCopy = tempImageView.getContext().openFileInput("file.png");
tempImageView.setImageBitmap(BitmapFactory.decodeStream(isCopy));