Android java.lang.NullPointerException:尝试获取空数组的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32298438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:19:09  来源:igfitidea点击:

Android java.lang.NullPointerException: Attempt to get length of null array

javaandroid

提问by manpreet parmar

Sorry for my formatting I am newbie to android as well as to stackoverflow cant submit all of my logcat due to some formatting error

抱歉我的格式我是 android 的新手,并且由于一些格式错误,stackoverflow 无法提交我的所有 logcat

in short I am getting following error:

简而言之,我收到以下错误:

at com.youmasti.mp3test.MainActivity.findsongs(MainActivity.java:45)
at com.youmasti.mp3test.MainActivity.onCreate(MainActivity.java:27)

Here is my code:

这是我的代码:

Main Activity

public class MainActivity extends AppCompatActivity {

ListView lv;
String items;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv= (ListView)findViewById(R.id.lvPlaylist);
    //File fTest = Environment.getExternalStorageDirectory();
    ArrayList<File> mySongs = findsongs(Environment.getExternalStorageDirectory());

    for (int i = 0; i < mySongs.size(); i++) {
        toast(mySongs.get(i).getName().toString());
    }
}

public ArrayList<File> findsongs(File root) {
    ArrayList<File> al= new ArrayList<File>();
    File[] file= root.listFiles();

    for (File singlefile : file) {
        if (singlefile.isDirectory() && !singlefile.isHidden()) {
            al.addAll(findsongs(singlefile));
        } else {
            if (singlefile.getName().endsWith(".mp3")) {
                al.add(singlefile);
            }
        }
    }
    return al;
}

public void toast (String text) {
    Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();
}

List item:

项目清单:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.youmasti.mp3test">    
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

LogCat

   08-30 10:39:30.227    2441-2441/? I/art﹕ Not late-enabling -Xcheck:jni        (already on)
   08-30 10:39:30.227    2441-2441/? I/art﹕ Late-enabling JIT
   08-30 10:39:30.229    2441-2441/? I/art﹕ JIT created with                code_cache_capacity=2MB compile_threshold=1000
   08-30 10:39:30.346    2441-2441/? W/System﹕ ClassLoader referenced        unknown path: /data/app/com.youmasti.mp3test-1/lib/x86
   08-30 10:39:30.527    2441-2441/com.youmasti.mp3test D/AndroidRuntime﹕        Shutting down VM
       --------- beginning of crash
   08-30 10:39:30.528    2441-2441/com.youmasti.mp3test E/AndroidRuntime﹕        FATAL EXCEPTION: main
       Process: com.youmasti.mp3test, PID: 2441
       java.lang.RuntimeException: Unable to start activity ComponentInfo       {com.youmasti.mp3test/com.youmasti.mp3test.MainActivity}:        java.lang.NullPointerException: Attempt to get length of null array
               at android.app.ActivityThread.performLaunchActivity       (ActivityThread.java:2416)
               at android.app.ActivityThread.handleLaunchActivity                     (ActivityThread.java:2476)
                      at android.app.ActivityThread.-wrap11                                                        (ActivityThread.java)
               at android.app.ActivityThread$H.handleMessage       (ActivityThread.java:1344)
               at android.os.Handler.dispatchMessage(Handler.java:102)
               at android.os.Looper.loop(Looper.java:148)
               at android.app.ActivityThread.main(ActivityThread.java:5417)
               at java.lang.reflect.Method.invoke(Native Method)
               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run       (ZygoteInit.java:726)
               at com.android.internal.os.ZygoteInit.main       (ZygoteInit.java:616)
        Caused by: java.lang.NullPointerException: Attempt to get length of        null array
               at com.youmasti.mp3test.MainActivity.findsongs       (MainActivity.java:45)
               at com.youmasti.mp3test.MainActivity.onCreate       (MainActivity.java:27)
               at android.app.Activity.performCreate(Activity.java:6237)
               at android.app.Instrumentation.callActivityOnCreate       (Instrumentation.java:1107)
               at android.app.ActivityThread.performLaunchActivity       (ActivityThread.java:2369)
   ????????????at android.app.ActivityThread.handleLaunchActivity       (ActivityThread.java:2476)
   ????????????at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1344)
   at android.os.Handler.dispatchMessage(Handler.java:102)

回答by Derek Fung

You have to point to us where is the line 45.

你必须向我们指出第 45 行在哪里。

But I would guess it is this line

但我猜是这条线

for (File singlefile : file) {

if yes, the problem is because listFiles()return null

如果是,问题是因为listFiles()返回null

It can return null for several reasons, root not exists, or root is not a folder, or most likely, as you are working with Android, you missed to add the permission in your manifest

它可能由于多种原因返回 null,root 不存在,或者 root 不是文件夹,或者很可能,当您使用 Android 时,您错过了在清单中添加权限

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

EDIT:

编辑:

after your edit, I believe your manifest has some problem

编辑后,我相信您的清单有问题

please check a sample here

请在此处查看示例

https://developer.android.com/samples/BasicContactables/AndroidManifest.html

https://developer.android.com/samples/BasicContactables/AndroidManifest.html

EDIT2:

编辑2:

https://developer.android.com/preview/features/runtime-permissions.html

https://developer.android.com/preview/features/runtime-permissions.html

for android 6.0, you need to request permission

对于 android 6.0,您需要请求权限

if (checkSelfPermission(Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (shouldShowRequestPermissionRationale(
            Manifest.permission.READ_CONTACTS)) {
        // Explain to the user why we need to read the contacts
    }

    requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
            MY_PERMISSIONS_REQUEST_READ_CONTACTS);

    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
    // app-defined int constant

    return;
}

回答by Andreas

Assume that MainActivity.java:45is this line:

假设这MainActivity.java:45是这一行:

for (File singlefile : file) {

It means that fileis null.

这意味着filenull

According to the javadoc of File.listFiles():

根据File.listFiles()的 javadoc :

Returns null if this abstract pathname does not denote a directory

如果此抽象路径名不表示目录,则返回 null

So value of rootis not a path name.

所以值root不是路径名。

回答by Androider

your

您的

  listFiles()

method may return null and root is not any path (use as)

方法可能返回 null 并且 root 不是任何路径(用作)

 Environment.getExternalStorageDirectory() + path like directory name