简体   繁体   中英

Android: NullPointer Exception (files)

I am trying to make an app and for that I need to list files. I have found some useful code and tailored it a bit for my needs. This is my (simple) code:

// List all files from specific directory
    public void listFiles(){

        // Path to directory to scane
        String path = Environment.getExternalStorageDirectory().toString()+"/Download/";

        // New file-instance
        File f = new File(path);

        // Get the textview to display message
        TextView textview = (TextView) findViewById(R.id.textView);

        textview.setText(f.toString());

        // List the files
        File file[] = f.listFiles();

        for(int i = 0; i < file.length; i++){
            Log.d("Files", "Filename: " + file[i].getName());
        }
    }

I know that this is caused by file.length in my for loop, but I don't understand why I get this error since it grabs the files in the right directory and I have files within that directory...

E

dit: This is my stack trace

java.lang.NullPointerException: Attempt to get length of null array
            at com.example.filemaker.MainActivity.listFiles(MainActivity.java:79)
            at com.example.filemaker.MainActivity$1.onClick(MainActivity.java:31)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

So what line make a NPE ? the file.length ? It means that file is null, looking at File javadoc, we can see the following description in the listFiles method return :

Returns: An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory , or if an I/O error occurs.

It seems that your path is not valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM