1

我正在尝试显示智能手机目录中存在的所有文件的列表。这是我正在处理的代码:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     final Button button = (Button) findViewById(R.id.button1);
     button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {


        File f = new File(Environment.getExternalStorageDirectory().toString()+"/DIRECTORY_MOVIES/TEAM_15"); 
        Log.d("Files", "Path: " +Environment.getExternalStorageDirectory().toString()+"/DIRECTORY_MOVIES/TEAM_15");
        File file[] = f.listFiles();
        Log.d("Files", "Size: "+ file.length);
        for (int i=0; i < file.length; i++)
        {
            Log.d("Files", "FileName:" + file[i].getName());
        }


         }
     });
}

因此,当我按下按钮时,我应该在 logcat 中看到文件夹中存在的所有文件:/DIRECTORY_MOVIES/TEAM_15 但这是出现的内容:

05-02 18:02:08.789: E/AndroidRuntime(2616): FATAL EXCEPTION: main
05-02 18:02:08.789: E/AndroidRuntime(2616): java.lang.NullPointerException
05-02 18:02:08.789: E/AndroidRuntime(2616):     at com.example.list.MainActivity$1.onClick(MainActivity.java:32)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at android.view.View.performClick(View.java:2506)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at android.view.View$PerformClick.run(View.java:9112)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at android.os.Handler.handleCallback(Handler.java:587)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at android.os.Handler.dispatchMessage(Handler.java:92)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at android.os.Looper.loop(Looper.java:130)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at android.app.ActivityThread.main(ActivityThread.java:3835)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at java.lang.reflect.Method.invokeNative(Native Method)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at java.lang.reflect.Method.invoke(Method.java:507)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
05-02 18:02:08.789: E/AndroidRuntime(2616):     at dalvik.system.NativeStart.main(Native Method)
05-02 18:07:08.812: I/Process(2616): Sending signal. PID: 2616 SIG: 9

怎么了??

4

2 回答 2

0

发生这种情况的可能原因是目录不存在,f.listFiles() 返回 null

于 2013-05-02T17:37:32.117 回答
0

在您的情况下, Environment.getExternalStorageDirectory() 返回 NULL。并且您尝试访问 NULL 变量的 .toString() 。

于 2013-05-02T17:41:35.607 回答