NullPointerException - 尝试获取空数组的长度(readDirectory()) [英] NullPointerException - Attempt to get length of null array (readDirectory())

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

问题描述

我有这里所示的代码。
我的问题是files.length的一个NullPointerException

  for(int i = 0; i< files.length ; i ++){

这是因为我有一个fail readDirectory()errno = 13

  File [] files = f.listFiles(); 

但是,当路径好的时候为什么我的readDirectory失败?

  package com.example.androidexplorer; 

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Environment;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ListActivity {

private List< String> item = null;
私人列表< String> path = null;
private String root;
private TextView myPath;

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPath =(TextView)findViewById(R.id.path);

root = Environment.getExternalStorageDirectory()。getPath();
getDir(root);
}

private void getDir(String dirPath)
{
myPath.setText(Location:+ dirPath);
item = new ArrayList< String>();
path = new ArrayList 文件f =新建文件(dirPath);

Log.v(Path:,dirPath);

Log.v(BEFORE,阅读失败之前...);
文件[] files = f.listFiles();
Log.v(AFTER,阅读失败后);


if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
items.add(../);
path.add(f.getParent());
}

Log.v(CRASH,1线之前崩溃); (int i = 0; i< files.length; i ++){
Log.v(AFTER CRASH,1 Line after crash);

文件文件=文件[i];

if(!file.isHidden()&& file.canRead()){
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName()+/);
} else {
item.add(file.getName());
}
}
}

ArrayAdapter< String> fileList =
new ArrayAdapter< String>(this,R.layout.row,item);
setListAdapter(fileList);
}

@Override
protected void onListItemClick(ListView l,View v,int position,long id){
// TODO自动生成的方法stub
文件文件= new File(path.get(position));

if(file.isDirectory())
{
if(file.canRead()){
getDir(path.get(position));
} else {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle([+ file.getName()+]文件夹无法读取!)
.setPositiveButton(OK,null).show();
}
} else {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle([+ file.getName ()+])
.setPositiveButton(OK,null).show();

}
}

}

LogCat:


 > 04-23 15:35:34.084:D / ResourcesManager(20672):创建新的
> AssetManager并设置为
> /data/app/com.example.androidexplorer-1/base.apk 04-23 15:35:34.104:
> I / art(20672):创建的应用程序空间
> /data/dalvik-cache/arm/data@app@com.example.androidexplorer-1@base.apk@classes.dex.art
>在0x76eb0000〜0x76f15ff8 04-23 15:35:34.104:I / art(20672):加载艺术
>档案:
> /data/dalvik-cache/arm/data@app@com.example.androidexplorer-1@base.apk@classes.dex.art
> 04-23 15:35:34.194:V / BitmapFactory(20672):
> DecodeImagePath(decodeResourceStream3):
> res / drawable-xxhdpi-v4 / ic_ab_back_holo_dark_am.png 04-23 15:35:34.204:
> V / BitmapFactory(20672):DecodeImagePath(decodeResourceStream3):
> res / drawable-xxhdpi-v4 / sym_def_app_icon.png 04-23 15:35:34.234:
> D / AbsListView(20672):Get MotionRecognitionManager 04-23 15:35:34.244:
> V / BitmapFactory(20672):DecodeImagePath(decodeResourceStream3):
> res / drawable-xhdpi-v4 / ic_launcher.png 04-23 15:35:34.254:
> V / Path:(20672):/ storage / emulated / 0 04-23 15:35:34.254:
> V / BEFORE(20672):阅读前失败... 04-23 15:35:34.254:
> E / File(20672):failed readDirectory()errno = 13 04-23 15:35:34.254:
> V / AFTER(20672):阅读失败后04-23 15:35:34.254:
> V / CRASH(20672):1崩溃前的行04-23 15:35:34.254:
> D / AndroidRuntime(20672):关闭VM 04-23 15:35:34.254:
> E / AndroidRuntime(20672):FATAL EXCEPTION:主04-23 15:35:34.254:
> E / AndroidRuntime(20672):进程:com.example.androidexplorer,PID:
> 20672 04-23 15:35:34.254:E / AndroidRuntime(20672):
> java.lang.RuntimeException:无法启动活动
> ComponentInfo {com.example.androidexplorer / com.example.androidexplorer.MainActivity}:
> java.lang.NullPointerException:尝试获取空数组的长度
> 04-23 15:35:34.254:E / AndroidRuntime(20672):at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
> 04-23 15:35:34.254:E / AndroidRuntime(20672):at
> android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
> 04-23 15:35:34.254:E / AndroidRuntime(20672):at
> android.app.ActivityThread.access $ 900(ActivityThread.java:172)04-23
> 15:35:34.254:E / AndroidRuntime(20672):at
> android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1422)
> 04-23 15:35:34.254:E / AndroidRuntime(20672):at
> android.os.Handler.dispatchMessage(Handler.java:102)04-23
> 15:35:34.254:E / AndroidRuntime(20672):at
> android.os.Looper.loop(Looper.java:145)04-23 15:35:34.254:
> E / AndroidRuntime(20672):at
> android.app.ActivityThread.main(ActivityThread.java:5834)04-23
> 15:35:34.254:E / AndroidRuntime(20672):at
> java.lang.reflect.Method.invoke(Native Method)04-23 15:35:34.254:
> E / AndroidRuntime(20672):at
> java.lang.reflect.Method.invoke(Method.java:372)04-23 15:35:34.254:
> E / AndroidRuntime(20672):at
> com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1388)
> 04-23 15:35:34.254:E / AndroidRuntime(20672):at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)04-23
> 15:35:34.254:E / AndroidRuntime(20672):导致:
> java.lang.NullPointerException:尝试获取空数组的长度
> 04-23 15:35:34.254:E / AndroidRuntime(20672):at
> com.example.androidexplorer.MainActivity.getDir(MainActivity.java:57)
> 04-23 15:35:34.254:E / AndroidRuntime(20672):at
> com.example.androidexplorer.MainActivity.onCreate(MainActivity.java:31)
> 04-23 15:35:34.254:E / AndroidRuntime(20672):at
> android.app.Activity.performCreate(Activity.java:6221)04-23
> 15:35:34.254:E / AndroidRuntime(20672):at
> android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
> 04-23 15:35:34.254:E / AndroidRuntime(20672):at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
> 04-23 15:35:34.254:E / AndroidRuntime(20672):... 10更多


更新



我的清单中出现了权限错误。
开始时我有:

 <?xml version =1.0encoding =utf-8 >?; 
< manifest xmlns:android =http://schemas.android.com/apk/res/android
package =com.spicysoftware.infoid
android:versionCode = 1
android:versionName =1.0>

< uses-sdk
android:minSdkVersion =15
android:targetSdkVersion =15/>

< application
android:allowBackup =true
android:icon =@ drawable / ic_launcher
android:label =@ string / app_name
android:theme =@ style / AppTheme
android:name =android.permission.READ_EXTERNAL_STORAGE>
< 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>
< activity android:name =。sysinfo>< / activity>
< activity android:name =。daten>< / activity>
< activity android:name =。storage>< / activity>
< activity android:name =org.achartengine.GraphicalActivity> < /活性GT;
< / application>

< / manifest>

并更新:

 <?xml version =1.0encoding =utf-8?> 
< manifest xmlns:android =http://schemas.android.com/apk/res/android
package =com.spicysoftware.infoid
android:versionCode = 1
android:versionName =1.0>

< uses-sdk
android:minSdkVersion =15
android:targetSdkVersion =15/>

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

< application
android:allowBackup =true
android:icon =@ drawable / 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>
< activity android:name =。sysinfo>< / activity>
< activity android:name =。daten>< / activity>
< activity android:name =。storage>< / activity>
< activity android:name =org.achartengine.GraphicalActivity> < /活性GT;
< / application>

< / manifest>


解决方案

  f。 listFiles()

如果路径不存在,则返回null。



请检查您的路径。



更新



Android还需要有权限读取某些文件。
您可能需要将其添加到您的清单中:

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

更多信息:



http://developer.android.com/reference/android/Manifest.permission.html


I have the code as shown here. My Problem is a NullPointerException at files.length

for(int i=0; i < files.length; i++){

It is caused because i have a "fail readDirectory() errno=13" at

File[] files = f.listFiles();

But why do I have a readDirectory fail when the path is good?

package com.example.androidexplorer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Environment;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ListActivity {

    private List<String> item = null;
    private List<String> path = null;
    private String root;
    private TextView myPath;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myPath = (TextView)findViewById(R.id.path);

        root = Environment.getExternalStorageDirectory().getPath();
        getDir(root);
    }

    private void getDir(String dirPath)
    {
        myPath.setText("Location: " + dirPath);
        item = new ArrayList<String>();
        path = new ArrayList<String>();
        File f = new File(dirPath);

Log.v("Path: ", dirPath);

        Log.v("BEFORE", "Before Reading Fail...");
        File[] files = f.listFiles();
        Log.v("AFTER", "After Reading Fail...");


        if(!dirPath.equals(root))
        {
            item.add(root);
            path.add(root);
            item.add("../");
            path.add(f.getParent());    
        }

        Log.v("CRASH", "1 Line before crash");
        for(int i=0; i < files.length; i++){
            Log.v("AFTER CRASH", "1 Line after crash");
            File file = files[i];

            if(!file.isHidden() && file.canRead()){
                path.add(file.getPath());
                if(file.isDirectory()){
                    item.add(file.getName() + "/");
                }else{
                    item.add(file.getName());
                }
            }   
        }

        ArrayAdapter<String> fileList =
                new ArrayAdapter<String>(this, R.layout.row, item);
        setListAdapter(fileList);   
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        File file = new File(path.get(position));

        if (file.isDirectory())
        {
            if(file.canRead()){
                getDir(path.get(position));
            }else{
                new AlertDialog.Builder(this)
                    .setIcon(R.drawable.ic_launcher)
                    .setTitle("[" + file.getName() + "] folder can't be read!")
                    .setPositiveButton("OK", null).show();  
            }   
        }else {
            new AlertDialog.Builder(this)
                    .setIcon(R.drawable.ic_launcher)
                    .setTitle("[" + file.getName() + "]")
                    .setPositiveButton("OK", null).show();

          }
    }

}

LogCat:

> 04-23 15:35:34.084: D/ResourcesManager(20672): creating new
> AssetManager and set to
> /data/app/com.example.androidexplorer-1/base.apk 04-23 15:35:34.104:
> I/art(20672): Created application space
> /data/dalvik-cache/arm/data@app@com.example.androidexplorer-1@base.apk@classes.dex.art
> at 0x76eb0000~0x76f15ff8 04-23 15:35:34.104: I/art(20672): Loaded art
> file:
> /data/dalvik-cache/arm/data@app@com.example.androidexplorer-1@base.apk@classes.dex.art
> 04-23 15:35:34.194: V/BitmapFactory(20672):
> DecodeImagePath(decodeResourceStream3) :
> res/drawable-xxhdpi-v4/ic_ab_back_holo_dark_am.png 04-23 15:35:34.204:
> V/BitmapFactory(20672): DecodeImagePath(decodeResourceStream3) :
> res/drawable-xxhdpi-v4/sym_def_app_icon.png 04-23 15:35:34.234:
> D/AbsListView(20672): Get MotionRecognitionManager 04-23 15:35:34.244:
> V/BitmapFactory(20672): DecodeImagePath(decodeResourceStream3) :
> res/drawable-xhdpi-v4/ic_launcher.png 04-23 15:35:34.254:
> V/Path:(20672): /storage/emulated/0 04-23 15:35:34.254:
> V/BEFORE(20672): Before Reading Fail... 04-23 15:35:34.254:
> E/File(20672): fail readDirectory() errno=13 04-23 15:35:34.254:
> V/AFTER(20672): After Reading Fail... 04-23 15:35:34.254:
> V/CRASH(20672): 1 Line before crash 04-23 15:35:34.254:
> D/AndroidRuntime(20672): Shutting down VM 04-23 15:35:34.254:
> E/AndroidRuntime(20672): FATAL EXCEPTION: main 04-23 15:35:34.254:
> E/AndroidRuntime(20672): Process: com.example.androidexplorer, PID:
> 20672 04-23 15:35:34.254: E/AndroidRuntime(20672):
> java.lang.RuntimeException: Unable to start activity
> ComponentInfo{com.example.androidexplorer/com.example.androidexplorer.MainActivity}:
> java.lang.NullPointerException: Attempt to get length of null array
> 04-23 15:35:34.254: E/AndroidRuntime(20672):    at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
> 04-23 15:35:34.254: E/AndroidRuntime(20672):    at
> android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
> 04-23 15:35:34.254: E/AndroidRuntime(20672):    at
> android.app.ActivityThread.access$900(ActivityThread.java:172) 04-23
> 15:35:34.254: E/AndroidRuntime(20672):  at
> android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
> 04-23 15:35:34.254: E/AndroidRuntime(20672):    at
> android.os.Handler.dispatchMessage(Handler.java:102) 04-23
> 15:35:34.254: E/AndroidRuntime(20672):  at
> android.os.Looper.loop(Looper.java:145) 04-23 15:35:34.254:
> E/AndroidRuntime(20672):    at
> android.app.ActivityThread.main(ActivityThread.java:5834) 04-23
> 15:35:34.254: E/AndroidRuntime(20672):  at
> java.lang.reflect.Method.invoke(Native Method) 04-23 15:35:34.254:
> E/AndroidRuntime(20672):    at
> java.lang.reflect.Method.invoke(Method.java:372) 04-23 15:35:34.254:
> E/AndroidRuntime(20672):    at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
> 04-23 15:35:34.254: E/AndroidRuntime(20672):    at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) 04-23
> 15:35:34.254: E/AndroidRuntime(20672): Caused by:
> java.lang.NullPointerException: Attempt to get length of null array
> 04-23 15:35:34.254: E/AndroidRuntime(20672):    at
> com.example.androidexplorer.MainActivity.getDir(MainActivity.java:57)
> 04-23 15:35:34.254: E/AndroidRuntime(20672):    at
> com.example.androidexplorer.MainActivity.onCreate(MainActivity.java:31)
> 04-23 15:35:34.254: E/AndroidRuntime(20672):    at
> android.app.Activity.performCreate(Activity.java:6221) 04-23
> 15:35:34.254: E/AndroidRuntime(20672):  at
> android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
> 04-23 15:35:34.254: E/AndroidRuntime(20672):    at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
> 04-23 15:35:34.254: E/AndroidRuntime(20672):    ... 10 more

UPDATE

Error was in my manifest with the permissions. What I had at the beginning:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.spicysoftware.infoid"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
         android:name="android.permission.READ_EXTERNAL_STORAGE">
        <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>
        <activity android:name=".sysinfo"></activity>
        <activity android:name=".daten"></activity>
        <activity android:name=".storage"></activity>
        <activity android:name="org.achartengine.GraphicalActivity"> </activity>
    </application>

</manifest>

And Updated:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.spicysoftware.infoid"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/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>
        <activity android:name=".sysinfo"></activity>
        <activity android:name=".daten"></activity>
        <activity android:name=".storage"></activity>
        <activity android:name="org.achartengine.GraphicalActivity"> </activity>
    </application>

</manifest>

解决方案

f.listFiles()

will return null if the path does not exist.

Please check your path.

Update

Android will also require a permission to read certain files. Maybe you need to add this to your manifest:

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

More information:

http://developer.android.com/reference/android/Manifest.permission.html

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

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