0

Edit: I realize this has been marked as a duplicate. But I believe this is somewhat different because I am not asking what a Null Pointer Exception is or how to fix it on a "programming fundamentals" level. If I am wrong on that then please correct me, but I believe that my question touches on a more intricate matter dealing with the Android framework. My issue has I have been trying to create a simple media player app following a basic YouTube tutorial but the app continues to force close immediately upon opening in the emulator. I am assuming it is some sort of configuration error because I have followed the tutorial to the letter. I have updated my code snippets according to the advice given. In the emulator the app force closes, however when I run the device on my phone the toast message "Null Array" is shown. My question, therefore, is why the program is not adding items into the mySongs ArrayList because there are .mp3 files in both the internal and external storage directories of my device. My code is as follows....

MainActivity.java:

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

    final ArrayList<File> mySongs = findSongs(Environment.getExternalStorageDirectory());

    items = new String[mySongs.size()];

    if (mySongs != null && !mySongs.isEmpty())
    {
        for (int i = 0; i < mySongs.size(); i++)
        {
            //toast(mySongs.get(i).getName().toString());
            items[i] = mySongs.get(i).getName().toString().replace("mp3", "").replace(".wav", "");
        }
    }
    else
    {
        //Log.e(getString(R.string.Exception));
        Toast.makeText(this, "Null Array", Toast.LENGTH_SHORT).show();

    }

    ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(), R.layout.song_layout, R.id.textView,items);
    lv.setAdapter(adp);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            startActivity(new Intent(getApplicationContext(), Player.class).putExtra("pos", position).putExtra("songlist", mySongs));
        }
    });

}

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

    for (File singleFile : files)
    {
        if (singleFile.isDirectory() && !singleFile.isHidden())
        {
            findSongs(singleFile);
        }
        else
        {
            if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav"))
            {
                al.add(singleFile);
            }
        }
    }
    return al;
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.user.mediaplayer.MainActivity">

<ListView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/lvPlaylist"
    android:layout_centerHorizontal="true"
    android:layout_alignParentTop="true" />
</RelativeLayout>

The log file:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.mediaplayer/com.example.user.mediaplayer.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.example.user.mediaplayer.MainActivity.findSongs(MainActivity.java:42)
    at com.example.user.mediaplayer.MainActivity.onCreate(MainActivity.java:28)
    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) 
    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)

I have also included:

uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.STORAGE"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

in the AndroidManifest.xml file. Any advice in the right direction would be appreciated. Thanks...

Mister Blue
  • 15
  • 1
  • 1
  • 6
  • Try it! @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.lvPlaylist); ArrayList mySongs = findSongs(Environment.getExternalStorageDirectory()); if(mySongs != null && !mySongs.isEmpty()){ for (int i = 0; i < mySongs.size(); i++) { toast(mySongs.get(i).getName().toString()); } }else{ Log.e("Array NULL") } } – Nguyễn Trung Hiếu Jul 28 '16 at 07:01
  • I will try it. Do you know why it is throwing the exception, though? Is it because there is nothing in the mySongs array? – Mister Blue Jul 28 '16 at 07:03
  • I thinks. Because File[] files = root.listFiles(); return NULL – Nguyễn Trung Hiếu Jul 28 '16 at 07:09
  • I tried that. It still throws the Null Pointer Exception. I am guessing it is because there are no items added into the array, but I am running it through the emulator. – Mister Blue Jul 28 '16 at 07:20
  • I think you are right. Therefore my issue lies more with the emulated storage not containing any data to add into the array than with the actual code. I kind of figured it was something along those lines. Thank you for your help. – Mister Blue Jul 28 '16 at 07:24

1 Answers1

0

You're trying to get the length of ArrayList mySongs. It the ArrayList received from findSongs() methods is empty it might result in the Null Pointer exception on the line mySongs.length

Check whether the ArrayList mySongs is null or not before performing any operations on it.

Varun Kumar
  • 1,241
  • 1
  • 9
  • 18