-2

I am trying to make a simple Music app, but when i am clicking the song name the app get crashed and it throwing an exception.

'Attempt to invoke virtual method Error setting data source java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object referenceat android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:117) at com.studios.debug.musicplayer.MusicService.playSong(MusicService.java:87) at com.studios.debug.musicplayer.RecyclerViewAdapter$MyViewHolder$1.onClick(RecyclerViewAdapter.java:58) at android.view.View.performClick(View.java:5207) at android.view.View$PerformClick.run(View.java:21177) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5438) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) 06-29 17:40:48.070 20284-20284/com.studios.debug.musicplayer E/AndroidRuntime: FATAL EXCEPTION: main Process: com.studios.debug.musicplayer, PID: 20284 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.prepareAsync()' on a null object reference at com.studios.debug.musicplayer.MusicService.playSong(MusicService.java:91) at com.studios.debug.musicplayer.RecyclerViewAdapter$MyViewHolder$1.onClick(RecyclerViewAdapter.java:58) at android.view.View.performClick(View.java:5207) at android.view.View$PerformClick.run(View.java:21177) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5438) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) on a null object reference'

Here is my code: MusicService.java

public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {
private final IBinder musicBind = new MusicBinder();
private MediaPlayer player;
private ArrayList<Song> songs;
private int songposition;

@Override
public void onCreate() {
    super.onCreate();
    songposition = 0;
    player = new MediaPlayer();
    initMusicPlayer();
}

public void initMusicPlayer() {
    player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);

}

public void setList(ArrayList<Song> theSong) {
    Log.e("Test", "" + theSong.size());
    this.songs = theSong;
}

@Override
public boolean onUnbind(Intent intent) {

    return false;

}

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

@Override
public void onCompletion(MediaPlayer mp) {

}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
   /* mp.reset();*/
    return false;
}

@Override
public void onPrepared(MediaPlayer mp) {
    mp.start();

}

public void playSong(ArrayList<Song> songs1) {
    Log.e("Test1", "" + songs1.size());

    Song playSong = songs1.get(songposition);
    long currSong = playSong.getID();
    Uri trackUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong);
    try {
        player.setDataSource(getApplicationContext(), trackUri);
    } catch (Exception e) {
        Log.e("MUSIC SERVICE", "Error setting data source", e);
    }
    player.prepareAsync();
}

public void setSong(int songIndex) {
    songposition = songIndex;
}

public class MusicBinder extends Binder {
    MusicService getService() {
        return MusicService.this;
    }
}
}

MainActivity.java

 public class MainActivity extends AppCompatActivity {
    private ArrayList<Song> songArrayList;
    private RecyclerView recyclerView;
    private RecyclerViewAdapter recyclerViewAdapter;
    private MusicService musicSrv;
    private Intent playIntent;
    private MediaPlayer player;
    private boolean musicBound = false;
    private ServiceConnection musicConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MusicBinder binder = (MusicBinder) service;
            musicSrv = binder.getService();
            musicSrv.setList(songArrayList);
            musicBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            musicBound = false;
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        if (playIntent == null) {
            playIntent = new Intent(this, MusicService.class);
            bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
            startService(playIntent);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                return;
            }
        }
        recyclerView = (RecyclerView) findViewById(R.id.songs_lists);
        songArrayList = new ArrayList<Song>();


        getSongList();
       Collections.sort(songArrayList, new Comparator<Song>() {
            @Override
            public int compare(Song o1, Song o2) {
                return o1.getTitle().compareTo(o2.getTitle());
            }
        });
        recyclerViewAdapter = new RecyclerViewAdapter(MainActivity.this, songArrayList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new SimpleDivider(MainActivity.this));
        recyclerView.setAdapter(recyclerViewAdapter);

    }

    public void getSongList() {
        ContentResolver contentResolver = getContentResolver();
        Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor musicCursor = contentResolver.query(musicUri, null, null, null, null);
        Log.e("test",""+musicCursor.getCount());
        if (musicCursor != null && musicCursor.moveToFirst()) {
            do {
                long thisId = musicCursor.getLong(musicCursor.getColumnIndex(MediaStore.Audio.Media._ID));
                String thisTitle = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String thisArtist = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));

                songArrayList.add(new Song(thisId, thisTitle, thisArtist));
            } while (musicCursor.moveToNext());
            musicCursor.close();

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;


    }

    @Override
    protected void onDestroy() {
        if (musicBound) unbindService(musicConnection);
        stopService(playIntent);
        musicSrv = null;
       /* player.stop();
        player.release();*/
        super.onDestroy();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_shuffle:
                break;
            case R.id.action_end:
                stopService(playIntent);
                musicSrv = null;
                System.exit(0);
                break;
        }
        return super.onOptionsItemSelected(item);
    }



}

RecyclerViewAdapter.java

 public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
        Context context;
        private ArrayList<Song> songs;
        private MusicService musicSrv;

        public RecyclerViewAdapter(Context c, ArrayList<Song> songs1) {
            this.songs = songs1;
            Log.e("Test", "" + songs.size());
            this.context = c;
        }

        @Override
        public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.row_list, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerViewAdapter.MyViewHolder holder, int position) {
            Song song = songs.get(position);
            holder.title.setText(song.getTitle());
            holder.artist.setText(song.getArtist());
        }

        @Override
        public int getItemCount() {
            return songs.size();
        }

        public class MyViewHolder extends RecyclerView.ViewHolder {
            public TextView title, artist;

            public MyViewHolder(View itemView) {
                super(itemView);
                title = (TextView) itemView.findViewById(R.id.song_title);
                artist = (TextView) itemView.findViewById(R.id.song_artist);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        musicSrv=new MusicService();
                        musicSrv.setSong(getLayoutPosition());
                        musicSrv.playSong(songs);
                    }
                });
            }
        }
    }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
A.Pant
  • 27
  • 1
  • 9
  • 2
    You do not need `getApplicationContext()` in any of these cases; `this` would work as well or better. Beyond that, please edit your question and post the entire Java stack trace associated with your exception. – CommonsWare Jun 29 '17 at 12:07
  • Kotlin code: applicationContext.contentResolver – Hamed Jaliliani Feb 18 '19 at 15:32

1 Answers1

2

You can't start service by creating new object: What you are doing is:

musicSrv=new MusicService();
                        musicSrv.setSong(getLayoutPosition());
                        musicSrv.playSong(songs);

and in playSong method you are trying to use getApplicationContext() which will be null as you need to start service instead of creating it's object like:

Intent intent = new Intent(context, MusicService.class);
        context.startService(intent);
Piyush
  • 2,589
  • 6
  • 38
  • 77