Android的显示java.lang.NullPointerException:尝试获取空数组长度 [英] Android java.lang.NullPointerException: Attempt to get length of null array

查看:14254
本文介绍了Android的显示java.lang.NullPointerException:尝试获取空数组长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我格式化我是新手到Android以及对计算器
斜面提交所有我的logcat由于一些格式错误

总之我收到以下错误:

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

下面是我的code:

 主要活动公共类MainActivity扩展AppCompatActivity {LV的ListView;
串的物品;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    LV =(ListView控件)findViewById(R.id.lvPlaylist);
    //文件FTEST = Environment.getExternalStorageDirectory();
    ArrayList的<文件> mySongs = findsongs(Environment.getExternalStorageDirectory());    的for(int i = 0; I< mySongs.size();我++){
        吐司(mySongs.get(I).getName()的toString());
    }
}公众的ArrayList<文件> findsongs(文件根目录){
    ArrayList的<文件>人=新的ArrayList<文件>();
    文件[] =文件root.listFiles();    对于(文件singlefile:文件){
        如果(singlefile.isDirectory()及&放大器;!singlefile.isHidden()){
            al.addAll(findsongs(singlefile));
        }其他{
            如果(singlefile.getName()。的endsWith(MP3)){
                al.add(singlefile);
            }
        }
    }
    返回人;
}公共无效吐司(字符串文本){
    Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_SHORT).show();
}

列表项:

 <?XML版本=1.0编码=UTF-8&GT?;<清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
包=com.youmasti.mp3test>
<使用许可权的android:NAME =android.permission.READ_EXTERNAL_STORAG​​E/>
<使用许可权的android:NAME =android.permission.WRITE_EXTERNAL_STORAG​​E/><应用
    机器人:allowBackup =真
    机器人:图标=@的mipmap / ic_launcher
    机器人:标签=@字符串/ APP_NAME
    机器人:主题=@风格/ AppTheme>
    <活动
        机器人:名字=。MainActivity
        机器人:标签=@字符串/ APP_NAME>
        &所述;意图滤光器>
            <作用机器人:名字=android.intent.action.MAIN/>
            <类机器人:名字=android.intent.category.LAUNCHER/>
        &所述; /意图滤光器>
    < /活性GT;
< /用途>

  LogCat中   10月8日至30日:39:30.227 2441年至2441年/? I /艺术:不晚启用-Xcheck:JNI(已上)
   10月8日至30日:39:30.227 2441年至2441年/? I /艺术:晚启用JIT
   10月8日至30日:39:30.229 2441年至2441年/? I /艺术:以$创建JIT C $ c_cache_capacity = 2MB compile_threshold = 1000
   10月8日至30日:39:30.346 2441年至2441年/? W /系统:ClassLoader的引用未知的路径:/data/app/com.youmasti.mp3test-1/lib/x86
   10月8日至30日:39:30.527 2441年至2441年/ com.youmasti.mp3test D / AndroidRuntime:关闭VM
       ---------崩溃的开始
   10月8日至30日:39:30.528 2441年至2441年/ com.youmasti.mp3test E / AndroidRuntime:致命异常:主要
       工艺:com.youmasti.mp3test,PID:2441
       了java.lang.RuntimeException:无法启动活动ComponentInfo {com.youmasti.mp3test / com.youmasti.mp3test.MainActivity}:显示java.lang.NullPointerException:尝试获取空数组长度
               在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
               在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                      在android.app.ActivityThread.-wrap11(ActivityThread.java)
               在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)
               在android.os.Handler.dispatchMessage(Handler.java:102)
               在android.os.Looper.loop(Looper.java:148)
               在android.app.ActivityThread.main(ActivityThread.java:5417)
               在java.lang.reflect.Method.invoke(本机方法)
               在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)
               在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
        显示java.lang.NullPointerException:引起尝试获取空数组长度
               在com.youmasti.mp3test.MainActivity.findsongs(MainActivity.java:45)
               在com.youmasti.mp3test.MainActivity.onCreate(MainActivity.java:27)
               在android.app.Activity.performCreate(Activity.java:6237)
               在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
               在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
   在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
   在android.app.ActivityThread.-wrap11(ActivityThread.java)
   在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)
   在android.os.Handler.dispatchMessage(Handler.java:102)


解决方案

您必须指向我们哪里是线45。

不过,我猜这是此行

 的(文件singlefile:文件){

如果有,这个问题是因为 listFiles()收益

它可以返回空值以下几个原因,根不存在,或者根本不是一个文件夹或最有可能的,因为你是与Android合作,你错过添加的权限在你的清单

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

编辑:

你的编辑后,我相信你的清单有一定的问题。

请点击这里查看样本

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

EDIT2:

https://developer.android.com/$p$ PVIEW /功能/运行时permissions.html

为Android 6.0,你需要申请许可

 如果(checkSelfPermission(Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED){    //我们应该显示一个解释?
    如果(shouldShowRequestPermissionRationale(
            Manifest.permission.READ_CONTACTS)){
        //向用户说明为什么我们需要读取联系人
    }    requestPermissions(新的String [] {} Manifest.permission.READ_CONTACTS,
            MY_PERMISSIONS_REQUEST_READ_CONTACTS);    // MY_PERMISSIONS_REQUEST_READ_CONTACTS是
    //应用程序定义的整型常量    返回;
}

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

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)

解决方案

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

But I would guess it is this line

for (File singlefile : file) {

if yes, the problem is because listFiles() return 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

<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

EDIT2:

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

for android 6.0, you need to request permission

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

这篇关于Android的显示java.lang.NullPointerException:尝试获取空数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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