使用File.listfiles()获取NullPointer异常

时间:2015-05-05 19:52:58

标签: java android nullpointerexception

所以我的Android画廊中有3个文件夹。我试图将这些文件夹的文件读入文件数组,然后从那里将图像源转换为实际的ImageViews

我的问题是我在引用我的文件数组时得到NullPointerException。这是一些代码:

// Get image files paths.
private File topsFolder = new File(Environment.getExternalStorageDirectory().getPath() + "/DressIt Tops/");
private File bottomsFolder = new File(Environment.getExternalStorageDirectory()
        .getPath() + "/DressIt Bottoms/");
private File shoesFolder = new File(Environment.getExternalStorageDirectory()
        .getPath() + "/DressIt Shoes/");

private File[] allTops = topsFolder.listFiles();
private File[] allBottoms = bottomsFolder.listFiles();
private File[] allShoes = shoesFolder.listFiles();

使用这些图像文件数组...

ImageAdapter topAdapter = new ImageAdapter(createList(allTops));
    topList.setAdapter(topAdapter);

    ImageAdapter midAdapter = new ImageAdapter(createList(allBottoms));
    midList.setAdapter(midAdapter);

    ImageAdapter botAdapter = new ImageAdapter(createList(allShoes));
    botList.setAdapter(botAdapter);

我的CreateList方法。错误是我引用list.length。

private List<ImageClass> createList(File[] list) {
    List<ImageClass> result = new ArrayList<ImageClass>();
    ImageClass img;
    Bitmap bmp;

    if (list.length > 0) {
        for (int i = 0; i < list.length; i++) {
            bmp = BitmapFactory.decodeFile(list[i].getAbsolutePath());
            img = new ImageClass(bmp);
            result.add(img);
        }
    } else
        result.add(new ImageClass(this.getResources().getIdentifier(
                "no_imgs_yet", "drawable", this.getPackageName())));
    return result;
}

就像我说的那样,错误是当我使用list.length引用其中一个文件数组时,例如我在第一个代码段中创建的allTops。

以下是LogCat错误消息:

05-05 19:43:49.409: D/dalvikvm(537): Not late-enabling CheckJNI (already on)
05-05 19:43:51.069: D/dalvikvm(537): GC_FOR_ALLOC freed 70K, 3% free 10185K/10439K, paused 63ms
05-05 19:43:51.079: I/dalvikvm-heap(537): Grow heap (frag case) to 10.566MB for 562516-byte allocation
05-05 19:43:51.139: D/dalvikvm(537): GC_CONCURRENT freed 1K, 3% free 10733K/11015K, paused 6ms+7ms
05-05 19:43:51.278: D/com.example.dressit(537): /mnt/sdcard/DressIt Tops
05-05 19:43:51.289: D/AndroidRuntime(537): Shutting down VM
05-05 19:43:51.289: W/dalvikvm(537): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
05-05 19:43:51.319: E/AndroidRuntime(537): FATAL EXCEPTION: main
05-05 19:43:51.319: E/AndroidRuntime(537): java.lang.RuntimeException: Unable to start activity 

ComponentInfo{com.example.dressit/com.example.dressit.MainActivity}: java.lang.NullPointerException
05-05 19:43:51.319: E/AndroidRuntime(537):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
05-05 19:43:51.319: E/AndroidRuntime(537):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
05-05 19:43:51.319: E/AndroidRuntime(537):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
05-05 19:43:51.319: E/AndroidRuntime(537):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
05-05 19:43:51.319: E/AndroidRuntime(537):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-05 19:43:51.319: E/AndroidRuntime(537):  at android.os.Looper.loop(Looper.java:137)
05-05 19:43:51.319: E/AndroidRuntime(537):  at android.app.ActivityThread.main(ActivityThread.java:4340)
05-05 19:43:51.319: E/AndroidRuntime(537):  at java.lang.reflect.Method.invokeNative(Native Method)
05-05 19:43:51.319: E/AndroidRuntime(537):  at java.lang.reflect.Method.invoke(Method.java:511)
05-05 19:43:51.319: E/AndroidRuntime(537):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-05 19:43:51.319: E/AndroidRuntime(537):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-05 19:43:51.319: E/AndroidRuntime(537):  at dalvik.system.NativeStart.main(Native Method)
05-05 19:43:51.319: E/AndroidRuntime(537): Caused by: java.lang.NullPointerException
05-05 19:43:51.319: E/AndroidRuntime(537):  at com.example.dressit.MainActivity.createList(MainActivity.java:125)
05-05 19:43:51.319: E/AndroidRuntime(537):  at com.example.dressit.MainActivity.onCreate(MainActivity.java:103)
05-05 19:43:51.319: E/AndroidRuntime(537):  at android.app.Activity.performCreate(Activity.java:4465)
05-05 19:43:51.319: E/AndroidRuntime(537):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-05 19:43:51.319: E/AndroidRuntime(537):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
05-05 19:43:51.319: E/AndroidRuntime(537):  ... 11 more
05-05 19:43:51.509: D/dalvikvm(537): GC_CONCURRENT freed 420K, 5% free 10747K/11271K, paused 6ms+5ms
05-05 19:44:25.629: I/Process(537): Sending signal. PID: 537 SIG: 9

我也得到了我的许可:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

很抱歉抛出这么多代码,但我觉得有人在这里找出问题是必要和充分的。

我现在花了几个小时在上面,并且认为我问社区!非常感谢大家。

编辑:感谢所有的反馈!这是我保存图像的代码。这应该显示已保存图像的所有路径。另外,我的LogCat说文件路径是/ mnt / sdcard / DressIt Tops。

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    String dirName;

    if (imageType == 1) {
        dirName = "DressIt Tops";
    } else if (imageType == 2) {
        dirName = "DressIt Bottoms";
    } else
        dirName = "DressIt Shoes";

    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            dirName);
    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(dirName, "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }
    return mediaFile;
}

1 个答案:

答案 0 :(得分:1)

根据File.listFiles()的文档,如果null不是目录,它将返回File

有三种(非常相似的)替代方案,为什么这是我的...

  1. (例如)String返回的Environment.getExternalStorageDirectory().getPath() + "/DressIt Tops/"并不代表有效目录(同样适用于..."/DressIt Bottoms/"和/或{{1} })。
  2. ..."/DressIt Shoes/"返回 ARE 有效路径 BUT 其中一个或另一个是文件而 NOT 是一个目录。
  3. 目录 DO 存在 BUT 您有一个错误的目录名称 - 请记住文件系统区分大小写。如果您已经创建了&#34; / DressIt Tops /&#34;目录为&#34;&#34; / dressIt tops /&#34; (例如),它不会被发现为有效路径。
  4. 还有一件事 - 永远不要假设Android文件系统上任何地方的任何路径 - 记录Strings实际返回的内容,检查它创建目录的位置,并检查是否所有内容都在正确的情况下。