获得空指针异常与File.listfiles() [英] Getting NullPointer exception with File.listfiles()

查看:2099
本文介绍了获得空指针异常与File.listfiles()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我在我的Andr​​oid库3个文件夹。我想这些文件夹的文件读入文件阵列,然后从那里,图像源转化为实际的 ImageViews

我的问题是我的引用文件阵时我得到 NullPointerException异常。下面是一些code:

  //获取图像文件的路径。
私人文件topsFolder =新的文件(Environment.getExternalStorageDirectory()的getPath()+/ DressIt上衣/);
私人文件bottomsFolder =新的文件(Environment.getExternalStorageDirectory()
        .getPath()+/ DressIt下装/);
私人文件shoesFolder =新的文件(Environment.getExternalStorageDirectory()
        .getPath()+/ DressIt鞋/);私人文件[] = allTops topsFolder.listFiles();
私人文件[] = allBottoms bottomsFolder.listFiles();
私人文件[] = allShoes shoesFolder.listFiles();

使用这些图像文件阵列...

  ImageAdapter topAdapter =新ImageAdapter(createList(allTops));
    topList.setAdapter(topAdapter);    ImageAdapter midAdapter =新ImageAdapter(createList(allBottoms));
    midList.setAdapter(midAdapter);    ImageAdapter botAdapter =新ImageAdapter(createList(allShoes));
    botList.setAdapter(botAdapter);

我CreateList方法。当我引用List.length的数字误差。

 私人列表<&的imageCLASS GT; createList(文件[]列表){
    清单<&的imageCLASS GT;结果=新的ArrayList<&的imageCLASS GT;();
    IMG的imageCLASS;
    BMP位图;    如果(List.length的数字大于0){
        的for(int i = 0; I< List.length的数字,我++){
            BMP = BitmapFactory.de codeFILE(名单[I] .getAbsolutePath());
            IMG =新的imageCLASS(BMP);
            result.add(IMG);
        }
    }其他
        result.add(新的imageCLASS(this.getResources()则getIdentifier(
                no_imgs_yet,可拉伸,this.getPackageName())));
    返回结果;
}

就像我说的,错误的是,当我使用List.length的数字来引用文件阵列,如我在第一个code段创建allTops之一。

和这里的LogCat中的错误信息:

  05-05 19:43:49.409:D / dalvikvm(537):不晚启用CheckJNI(已上)
05-05 19:43:51.069:D / dalvikvm(537):GC_FOR_ALLOC释放70K,免费10185K / 10439K 3%,暂停63毫秒
05-05 19:43:51.079:I / dalvikvm堆(537):成长堆(frag的情况下),以10.566MB为562516字节分配
05-05 19:43:51.139:D / dalvikvm(537):GC_CONCURRENT释放1K,免费3%10733K / 11015K,暂停为6ms + 7毫秒
05-05 19:43:51.278:D / com.example.dressit(537):到/ mnt / SD卡/ DressIt上衣
05-05 19:43:51.289:D / AndroidRuntime(537):关闭VM
05-05 19:43:51.289:W / dalvikvm(537):主题ID = 1:螺纹未捕获的异常(组= 0x409961f8)退出
05-05 19:43:51.319:E / AndroidRuntime(537):致命异常:主要
05-05 19:43:51.319:E / AndroidRuntime(537):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.dressit / com.example.dressit.MainActivity}:显示java.lang.NullPointerException
05-05 19:43:51.319:E / AndroidRuntime(537):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
05-05 19:43:51.319:E / AndroidRuntime(537):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
05-05 19:43:51.319:E / AndroidRuntime(537):在android.app.ActivityThread.access $ 600(ActivityThread.java:122)
05-05 19:43:51.319:E / AndroidRuntime(537):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1146)
05-05 19:43:51.319:E / AndroidRuntime(537):在android.os.Handler.dispatchMessage(Handler.java:99)
05-05 19:43:51.319:E / AndroidRuntime(537):在android.os.Looper.loop(Looper.java:137)
05-05 19:43:51.319:E / AndroidRuntime(537):在android.app.ActivityThread.main(ActivityThread.java:4340)
05-05 19:43:51.319:E / AndroidRuntime(537):在java.lang.reflect.Method.invokeNative(本机方法)
05-05 19:43:51.319:E / AndroidRuntime(537):在java.lang.reflect.Method.invoke(Method.java:511)
05-05 19:43:51.319:E / AndroidRuntime(537):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
05-05 19:43:51.319:E / AndroidRuntime(537):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-05 19:43:51.319:E / AndroidRuntime(537):在dalvik.system.NativeStart.main(本机方法)
05-05 19:43:51.319:E / AndroidRuntime(537):致:显示java.lang.NullPointerException
05-05 19:43:51.319:E / AndroidRuntime(537):在com.example.dressit.MainActivity.createList(MainActivity.java:125)
05-05 19:43:51.319:E / AndroidRuntime(537):在com.example.dressit.MainActivity.onCreate(MainActivity.java:103)
05-05 19:43:51.319:E / AndroidRuntime(537):在android.app.Activity.performCreate(Activity.java:4465)
05-05 19:43:51.319:E / AndroidRuntime(537):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-05 19:43:51.319:E / AndroidRuntime(537):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
05-05 19:43:51.319:E / AndroidRuntime(537):11 ...更多
05-05 19:43:51.509:D / dalvikvm(537):GC_CONCURRENT释放420K,免费5%10747K / 11271K,暂停为6ms + 5ms的
05-05 19:44:25.629:I /流程(537):发送信号。 PID:537 SIG:9

我有我的地方的权限,以及:

 <使用许可权的android:NAME =android.permission.READ_EXTERNAL_STORAG​​E/>

对不起这么多code扔,但我觉得有必要和足够的人来这里弄清楚这个问题。

我对现在花了几个小时,想通我问这个社会!非常感谢大家。

编辑:感谢所有的反馈!这里是我的code,节省了拍摄的图像。这将显示保存的图像的所有道路。另外,我的LogCat中说,该文件的路径是/ mnt / SD卡/ DressIt上衣。

  / **保存图像或视频*创建文件/
私有静态文件getOutputMediaFile(整型){
    //为了安全起见,你应该检查SD卡安装
    //这样做之前,使用Environment.getExternalStorageState()。    字符串目录名;    如果(IMAGETYPE == 1){
        目录名=DressIt强;
    }否则如果(IMAGETYPE == 2){
        目录名=DressIt下装
    }其他
        目录名=DressIt鞋;    文件mediaStorageDir =新的文件(
            环境
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            目录名);
    //如果你想共享的创建的映像这个位置效果最佳
    //应用程序之间以及您的应用程序已被卸载后仍然存在。    //创建存储目录,如果它不存在
    如果(!mediaStorageDir.exists()){
        如果(!mediaStorageDir.mkdirs()){
            Log.d(目录名称,无法创建目录);
            返回null;
        }
    }    //创建一个媒体文件名
    字符串的timeStamp =新的SimpleDateFormat(YYYYMMDD_HHMMSS)
            .format(新的Date());
    文件媒体文件;
    如果(类型== MEDIA_TYPE_IMAGE){
        媒体文件=新的文件(mediaStorageDir.getPath()+文件分割符
                +IMG_+ +的timeStamp.JPG);
    }否则如果(类型== MEDIA_TYPE_VIDEO){
        媒体文件=新的文件(mediaStorageDir.getPath()+文件分割符
                +VID_+的timeStamp +.MP4);
    }其他{
        返回null;
    }
    返回媒体文件;
}


解决方案

据该文档的 File.listFiles(),它将返回如果文件是不是一个目录。

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


  1. 字符串通过(例如)... Environment.getExternalStorageDirectory()返回的getPath()+/ DressIt上衣/不会重新present一个有效的目录(相同的,可以申请 .../ DressIt下装/和/或 .../ DressIt鞋/)。

  2. 字符串返回的的有效路径 BUT 的一种或另一种人是文件和 NOT 的目录中。

  3. 的目录的 DO 的存在的的你有目录名一个错字 - 记住文件系统是区分大小写的。如果你创建了/ DressIt上衣/目录/ dressIt上衣/(例如),它不会被发现为有效路径。

还有一件事 - 永远不要假设在Android文件系统的任何地方的任何路径 - 记录什么 Environment.getExternalStorageDirectory()的getPath()实际上返回,检查它就是你创造并检查你的目录有正确的情况下,一切。

So I have 3 folders in my Android Gallery. I am trying to read the files of these folders into File arrays and then, from there, translate the image source into actual ImageViews.

My problem is that I'm getting NullPointerException when referencing my File array. Here is some code:

// 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();

Using these image File arrays...

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);

My CreateList method. The error is when I reference 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;
}

Like I said, the error is when I use list.length to reference one of the File arrays, such as allTops that I created in the first code segment.

And here are the LogCat error messages:

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

I do have my permission in place, as well:

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

Sorry to throw in so much code, but I feel like it is necessary and sufficient for someone to figure out the issue here.

I've spent a few hours on it now and figured I'd ask the community! Thanks so much everyone.

EDIT: Thanks for all of the feedback! Here is my code that saves images taken. This should show you all the path of the saved images. Also, my LogCat says that the file path is /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;
}

解决方案

According to the documentation for File.listFiles(), it will return null if the File is not a directory.

There are three (very similar) alternatives as to why this my be...

  1. The String returned by (for example)... Environment.getExternalStorageDirectory().getPath() + "/DressIt Tops/" doesn't represent a valid directory (the same may apply for ..."/DressIt Bottoms/" and/or ..."/DressIt Shoes/").
  2. The Strings returned ARE valid paths BUT one or other of them is a file and NOT a directory.
  3. The directories DO exist BUT you have a typo with the directory name - remember the filesystem is case-sensitive. If you've created the "/DressIt Tops/" directory as ""/dressIt tops/" (for example), it won't be found as a valid path.

One more thing - never assume any path to anywhere on the Android filesystem - log what Environment.getExternalStorageDirectory().getPath() actually returns, check it's where you created the directories and also check you have everything in the correct case.

这篇关于获得空指针异常与File.listfiles()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆