-1

当我尝试在 sd 卡上检索保存的图片时遇到一些问题。

基本上,我在拍摄图像时使用的代码是:

    if(now==null){

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            now = sdf.format(new Date());
        }

        myDirVids=new File(Environment.getExternalStorageDirectory()+"/TimelapseVideos");
        if(!myDirVids.exists()){
            myDirVids.mkdirs();
        }
        myDirPhotos=new File(Environment.getExternalStorageDirectory()+"/TimelapsePhotos");
        if(!myDirPhotos.exists()){
            myDirPhotos.mkdirs();
        }

        myDir=new File(myDirPhotos+"/timelapse"+now);
        myDir.mkdirs();
        DecimalFormat decimalFormat = new DecimalFormat("00000");
        imagename = "Image-"+ decimalFormat.format(num) +".jpg";
        file = new File (myDir, imagename);
        if (file.exists ()) file.delete (); 
        try {
            FileOutputStream fos = new FileOutputStream(file);

            fos.write(data);
            fos.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

就在这行之后,我尝试检索保存的图像并且我得到一个 NullPointerException 因为它似乎不可用:

    Log.d(TAG, file.getAbsolutePath());
    Log.d(TAG, imagename);

try { 
Thread.sleep(800); 
} catch (InterruptedException e) {              
e.printStackTrace();
}

我在第一行得到 nullPointerException,Log.d(TAG, file.getAbsolutePath());

但是如果我把这条线放在睡眠之后,就不会抛出 nullPointerException。睡眠必须优于 500 毫秒才能不出现任何错误。

我不知道问题出在哪里,但我相信当 FileOutPutStream 操作完成时,智能手机仍在将数据保存在 sd 卡中。如果我让电话一段时间(0.5-1 秒),问题就会消失,因为写入过程已经完成。

我的问题是:

有什么方法可以知道写入操作何时完成?

4

2 回答 2

1

好的,我终于解决了我的问题。

正如我所说,当我试图访问刚刚保存的图像时,我得到了 NullPointerException。保存后(在 500 毫秒内)“文件”变量为空(出于某种我不知道的原因)。

所以我只是添加了这一行,以便知道文件何时不为空:

while(file==null){}

//retrieve file

感谢您的时间。

于 2013-08-28T09:14:00.677 回答
1

要检查文件是否存在,您可以执行 -

File file = new File(getExternalCacheDirectory(), YOUR_FILE_NAME);
if (file.exists()) {
  // Exists
} else {
  // Doesn't exist
}

此外,您可以使用MediaScannerConnection扫描文件。

于 2013-08-27T15:46:48.897 回答