0

I need a way to show me all .txt files of the Storage in a ListView.

So, I have written this function but the app crash. Why ?

Main Activity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv = (ListView) findViewById(R.id.lvPlaylist);

    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||  Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState())) {
        ArrayList<File> mySongs = findTxT(Environment.getExternalStorageDirectory());
    }
}

public ArrayList<File> findTxT(File root){

    ArrayList<File> al = new ArrayList<File>();

    File[] files = root.listFiles();
    for(File singleFile : files){
       if(singleFile.isDirectory()){

       }else{
           if(singleFile.getName().endsWith(".txt")){
               al.add(singleFile);

           }

       }
    }

    return al;
}

Activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lvPlaylist"
        android:layout_alignParentTop="true"
        android:choiceMode="singleChoice" />

</RelativeLayout>

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shon.rodry.elegantxt" >

    <uses-permission android:name="android.permission.READ_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>

</manifest>

Stacktrace:

10-20 09:38:50.320    3405-3405/? I/art﹕ Late-enabling -Xcheck:jni
10-20 09:38:50.387    3405-3405/com.shon.rodry.elegantxt W/System﹕ ClassLoader referenced unknown path: /data/app/com.shon.rodry.elegantxt-1/lib/arm
10-20 09:38:50.620    3405-3405/com.shon.rodry.elegantxt D/AndroidRuntime﹕ Shutting down VM
10-20 09:38:50.625    3405-3405/com.shon.rodry.elegantxt E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.shon.rodry.elegantxt, PID: 3405
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.shon.rodry.elegantxt/com.shon.rodry.elegantxt.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5443)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
     Caused by: java.lang.NullPointerException: Attempt to get length of null array
            at com.shon.rodry.elegantxt.MainActivity.findTxT(MainActivity.java:34)
            at com.shon.rodry.elegantxt.MainActivity.onCreate(MainActivity.java:25)
            at android.app.Activity.performCreate(Activity.java:6245)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5443)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
xRobot
  • 25,579
  • 69
  • 184
  • 304
  • 2
    Can you provide the stacktrace? – ehehhh Oct 20 '16 at 07:31
  • 3
    Please post your crash log here... – Md Abdul Gafur Oct 20 '16 at 07:31
  • @ehehhh done :) – xRobot Oct 20 '16 at 07:41
  • Crash happens in your `findTxt` method, line 34. I'm guessing `root.listFiles()` returns null? – ehehhh Oct 20 '16 at 07:43
  • Possible duplicate of [Android permission doesn't work even if I have declared it](http://stackoverflow.com/questions/32635704/android-permission-doesnt-work-even-if-i-have-declared-it) – Mike M. Oct 20 '16 at 07:44
  • @xRobot: simply error means `files` is null so add null check before iterating files array because `listFiles` method returning null when no file found inside path which is returned by `Environment.getExternalStorageDirectory()` – ρяσѕρєя K Oct 20 '16 at 07:44
  • and also see [list all files in the folder and also sub folders](http://stackoverflow.com/questions/14676407/list-all-files-in-the-folder-and-also-sub-folders) which probably help you – ρяσѕρєя K Oct 20 '16 at 07:46

1 Answers1

1

The method should look like this:

public ArrayList<File> findTxT(File root){
    ArrayList<File> al = new ArrayList<File>();
    File[] files = root.listFiles();
    if(files == null) //This check will fix the crash
        return al;
    for(File singleFile : files){
       if(singleFile.isDirectory()){

       }else{
           if(singleFile.getName().endsWith(".txt")){
               al.add(singleFile);
           }
       }
    }

    return al;
}

You still need to find out why the array is null. You may either be passing the wrong root file, or it may be a permission problem (permission not added to manifest and/or permission not allowed on api 23+).

Kelevandos
  • 7,024
  • 2
  • 29
  • 46
  • Thanks now it doesn't crash anymore. I am developing by using API 10 but to test the app I am using Android 6 ( API 23 ). So it maybe is a permission problem but I have added it to manifest as you can see above. – xRobot Oct 20 '16 at 08:00
  • Try going into app settings of your app (on phone), then Permissions and then enable Storage there manually. Try running your code then. If this works, then you will need to implement permission enabling in your app. – Kelevandos Oct 20 '16 at 08:02