androidjava.lang.class

java.lang.NullPointerException while creating a Mp3Player


This was the code I was writing to start a Mp3Player by watching a video tutorial. I searched a lot for this issue but unable to sort out the error. After running this code , I am getting java.lang.NullPointerException error. My code looks somewhat like this:

package com.songs.playit;

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

import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;



public class MainActivity extends ListActivity {

    @SuppressLint("SdCardPath") private final static String sdPath = new String("/extSdCard/");
    private List<String> songs = new ArrayList<String>();
    MediaPlayer mp =new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.fragment_main);
        updatePlaylist();

     Button StopPlay = (Button) findViewById(R.id.stopBtn);
        StopPlay.setOnClickListener(new OnClickListener(){          

            public void onClick(View v){
            mp.stop();
            }       

    });
    }
    private void updatePlaylist() {
        // TODO Auto-generated method stub

        File home = new File(sdPath);
             if(home.listFiles(new Mp3Filter()).length>0){
        for(File file: home.listFiles(new Mp3Filter())){
        songs.add(file.getName());
        }

        ArrayAdapter<String> songList = new ArrayAdapter<String> (this , R.layout.songs_item , songs);
    setListAdapter(songList);
    }
    }

    protected void onListItemClick(ListView list , View v , int position , long id){
        try{
            mp.reset();
                  mp.setDataSource(sdPath + songs.get(position));
            mp.prepare();
            mp.start();
        }
        catch(IOException e){
            Log.v(getString(R.string.app_name), e.getMessage());
        }
    }

}
 class Mp3Filter implements FilenameFilter {

    @Override
    public boolean accept(File dir, String filename) {
        // TODO Auto-generated method stub
        {
        return (filename.endsWith(".mp3"));
    }

    }

}

And this was the error I was getting :

08-13 05:06:11.630: D/dalvikvm(762): GC_FOR_ALLOC freed 43K, 4% free 2900K/3008K, paused 34ms, total 37ms
08-13 05:06:11.630: I/dalvikvm-heap(762): Grow heap (frag case) to 3.370MB for 500416-byte allocation
08-13 05:06:11.680: D/dalvikvm(762): GC_FOR_ALLOC freed 2K, 4% free 3386K/3500K, paused 40ms, total 40ms
08-13 05:06:11.780: D/AndroidRuntime(762): Shutting down VM
08-13 05:06:11.780: W/dalvikvm(762): threadid=1: thread exiting with uncaught exception (group=0xb3a3fba8)
08-13 05:06:11.800: E/AndroidRuntime(762): FATAL EXCEPTION: main
08-13 05:06:11.800: E/AndroidRuntime(762): Process: com.songs.playit, PID: 762
08-13 05:06:11.800: E/AndroidRuntime(762): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.songs.playit/com.songs.playit.MainActivity}: java.lang.NullPointerException
08-13 05:06:11.800: E/AndroidRuntime(762):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-13 05:06:11.800: E/AndroidRuntime(762):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-13 05:06:11.800: E/AndroidRuntime(762):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-13 05:06:11.800: E/AndroidRuntime(762):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-13 05:06:11.800: E/AndroidRuntime(762):  at android.os.Handler.dispatchMessage(Handler.java:102)
08-13 05:06:11.800: E/AndroidRuntime(762):  at android.os.Looper.loop(Looper.java:136)
08-13 05:06:11.800: E/AndroidRuntime(762):  at android.app.ActivityThread.main(ActivityThread.java:5017)
08-13 05:06:11.800: E/AndroidRuntime(762):  at java.lang.reflect.Method.invokeNative(Native Method)
08-13 05:06:11.800: E/AndroidRuntime(762):  at java.lang.reflect.Method.invoke(Method.java:515)
08-13 05:06:11.800: E/AndroidRuntime(762):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-13 05:06:11.800: E/AndroidRuntime(762):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-13 05:06:11.800: E/AndroidRuntime(762):  at dalvik.system.NativeStart.main(Native Method)
08-13 05:06:11.800: E/AndroidRuntime(762): Caused by: java.lang.NullPointerException
08-13 05:06:11.800: E/AndroidRuntime(762):  at com.songs.playit.MainActivity.updatePlaylist(MainActivity.java:47)
08-13 05:06:11.800: E/AndroidRuntime(762):  at com.songs.playit.MainActivity.onCreate(MainActivity.java:32)
08-13 05:06:11.800: E/AndroidRuntime(762):  at android.app.Activity.performCreate(Activity.java:5231)
08-13 05:06:11.800: E/AndroidRuntime(762):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-13 05:06:11.800: E/AndroidRuntime(762):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-13 05:06:11.800: E/AndroidRuntime(762):  ... 11 more
08-13 05:06:18.430: I/Process(762): Sending signal. PID: 762 SIG: 9

Please help me out. Thanks in advance


Solution

  • There is no guarantee that the path to the SD card will be /extSdCard/

    If you want to get the path to the external storage you should use Environment.getExternalStorageDirectory().getAbsolutePath()

    So if no file is found at path /extSdCard/ home will be null

    And when you try to call home.listFiles(new Mp3Filter()) you will get a NullPointerException as you are trying to call the litFiles method on a null object

    So change

    private final static String sdPath = new String("/extSdCard/");
    

    to

    private final static String sdPath = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
    

    Also if you are not sure that whether a file exists or not use exists() method of the File to check