1

I'm trying to set a song on MediaPlayer with URL, but for some reason, I keep getting an error like this:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setDataSource(java.lang.String)' on a null object reference
    at com.example.musicplayerjd.PlayerActivity.getIntentMethod(PlayerActivity.java:490)
    at com.example.musicplayerjd.PlayerActivity.onCreate(PlayerActivity.java:56)
    at android.app.Activity.performCreate(Activity.java:7893)
    at android.app.Activity.performCreate(Activity.java:7880)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3283)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:224) 
    at android.app.ActivityThread.main(ActivityThread.java:7562) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 
    2020-12-25 18:22:29.435 1628-2212/? E/InputDispatcher: channel 'b9823c3 
    com.example.musicplayerjd/com.example.musicplayerjd.MainActivity (server)' ~ Channel is 
    unrecoverably broken and will be disposed!

Can't understand why it says that it refers to a null object. I have checked much time that the data I insert to it is not null. I'm inserting this URL https://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 and every time that I try to play music it crashes with this error message.

This is the code - Simple code

mediaPlayer.setDataSource(listSongs.get(position).getURL());
mediaPlayer.prepareAsync();
mediaPlayer.start();

*ListSongs holds a list of URLs

E.Bolandian
  • 553
  • 10
  • 35

1 Answers1

0
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setDataSource(java.lang.String)' on a null object reference
    at com.example.musicplayerjd.PlayerActivity.getIntentMethod(PlayerActivity.java:490)

This crash means that your MediaPlayer object is null, not the argument to setDataSource. Please initialize mediaPlayer properly.

  • that's weird because I initialize it `mediaPlayer = MediaPlayer.create(getApplicationContext(), listSongs.get(position).getSongId());` So I'm not sure what I'm doing wrong.. – E.Bolandian Dec 26 '20 at 11:25