-1

I am trying to make a simple service to play mp3 files. Below is my code for Service class.

public class MyService extends Service {

    private IBinder iBinder = new LocalBinder();
    private ArrayList<Song> songsList;
    private MediaPlayer player;

    @Override
    public void onCreate() {
        player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.reset();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return iBinder;
    }

    public class LocalBinder extends Binder{
        public MyService getService() {
            return MyService.this;
        }
    }

    public void setSongsList(ArrayList<Song> songsList) {
        this.songsList = songsList;
    }

    public void playSong(Song song) {
        try {
            player.setDataSource(getApplicationContext(), Uri.parse(song.getPath()));
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

And this is my Activity class.

public class MyActivity extends Activity {

    private MyService myService;
    private boolean mBound;
    private ArrayList<Song> songsList = new ArrayList<Song>();
    private Uri musicUri;
    private ContentResolver musicResolver;
    private int count;

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mBound = true;
            MyService.LocalBinder binder = (MyService.LocalBinder)iBinder;
            myService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBound = false;
            //myService = null;
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        Intent i = new Intent(this, MyService.class);
        bindService(i, serviceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mBound) {
            myService.unbindService(serviceConnection);
            mBound = false;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        musicResolver = getContentResolver();
        prepareListOfSongsAndAlbumMap();
        /*for(Song s: songsList) {
            Log.i("Song", s.getTitle());
        }*/
        if(myService == null) {
            Log.i("NULL SERVICE", "NULL");
        }
        myService.setSongsList(songsList);
        myService.playSong(songsList.get(3));

    }

    private void prepareListOfSongsAndAlbumMap() {
        this.musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        String[] projection = null;
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
        String selectionMimeType = MediaStore.Audio.Media.IS_MUSIC + " !=0";

        Cursor musicCursor = musicResolver.query(musicUri, projection, selectionMimeType, null, sortOrder);
        count = musicCursor.getCount();
        if(musicCursor != null && musicCursor.moveToFirst()) {
            do {
                String path = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String title = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String album = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                String artist = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int artistId = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
                int albumId = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                int trackId = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.TRACK));
                long duration = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.DURATION));

                Uri sArtworkUri = Uri
                        .parse("content://media/external/audio/albumart");
                Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);

                Song song = new Song(path, title, album, artist, albumId, trackId, duration, albumArtUri.toString(), artistId);
                songsList.add(song);

            }while(musicCursor.moveToNext());
        }
        musicCursor.close();
    }
}

When i try to run this code then I am getting NullPointerException, myService is not getting created. I am not able to figure out where i am making the mistake.

Following is the log details.

  java.lang.RuntimeException: Unable to start activity ComponentInfo{music.skumar.com.servicetest/music.skumar.com.servicetest.MyActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2268)
        at android.app.ActivityThread.access$600(ActivityThread.java:148)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1263)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5162)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572)
        at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at music.skumar.com.servicetest.MyActivity.onCreate(MyActivity.java:76)
        at android.app.Activity.performCreate(Activity.java:5135)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at com.lbe.security.service.core.client.b.x.callActivityOnCreate(Unknown Source)
  atandroid.app.ActivityThread.performLaunchActivity(ActivityThread.java:2182) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2268)
            at android.app.ActivityThread.access$600(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1263)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5162)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572)
            at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
            at dalvik.system.NativeStart.main(Native Method)
Sumit Kumar
  • 402
  • 1
  • 6
  • 26

1 Answers1

1

myService will be null in onCreate(), at least when your activity is first created. Not only do you not call bindService() until onStart() (which happens after onCreate()), but bindService() is asynchronous. Do not attempt to use myService until onServiceConnected() is called.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491