【问题标题】:NullPointerException retrieving saved picture on the sd-cardNullPointerException 检索 sd 卡上保存的图片
【发布时间】:2013-08-27 15:43:05
【问题描述】:

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

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

    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 秒),问题就会消失,因为写入过程已经完成。

我的问题是:

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

【问题讨论】:

  • Just before this lines -- 你的意思是Just AFTER these lines 吗?
  • @PeterK。抱歉,我是说之后。
  • 你上面代码中file变量的类型和值是什么?
  • @unluddite file = new File (myDir, imagename);其中 myDir 是我要保存图像的路径的字符串,而 imagename 是图像的名称,例如“image-00001.jpg”
  • 您是否复制/粘贴了写出文件的代码? FileOutputStream 类没有将byte[] 作为参数的write() 方法。您还可以包含用于尝试读取文件的代码吗?哪一行代码实际上抛出了异常?

标签: java android io nullpointerexception


【解决方案1】:

要检查文件是否存在,你可以这样做-

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

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

【讨论】:

  • 我正在使用一个文件夹将图像保存在 sd 卡上,而不是缓存。我将文件定义为:new File(myDir,imagename)。如果我尝试 file.exists() 然后 NullPointerException 被抛出。如果我在执行 fos.write(data) 后等待大约 1 秒,则不会引发 nullPointerException。
  • @MatiesPons 不能使用 if(new File(Environment.getExternalStorageDirectory().toString()).exists()){}
【解决方案2】:

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

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

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

while(file==null){}

//retrieve file

感谢您的宝贵时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    相关资源
    最近更新 更多