It's simple, there is a ListView and a few items, there is also a MediaPlayer that plays streaming audio when you click on items. The problem is that the audio overlaps each other. For example, you click on the first item, playback is in progress, then on the second and second one it overlaps with the first one and it seems to me that it will be with each item.

The question is how to properly stop the previous one and start a new one?

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView)findViewById(R.id.listView); final String[] spisok = new String[] {getResources().getString(R.string.europa), getString(R.string.topnews), getString(R.string.diskoteka90) }; final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, spisok); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { if (position == 0){ playRadio1(); } if (position == 1){ playRadio2(); } if (position == 2){ playRadio3(); } } }); } public void playRadio1() { String link1 = "http://ep128.hostingradio.ru:8030/ep128"; mediaPlayer = MediaPlayer.create(this, Uri.parse(link1)); mediaPlayer.start(); } public void playRadio2() { String link2 = "http://hls-01-europaplus-new.emgsound.ru/27/128/playlist.m3u8"; mediaPlayer = MediaPlayer.create(this, Uri.parse(link2)); mediaPlayer.start(); } 

    2 answers 2

    Before calling mediaPlayer.start() check if the track already plays:

     if(mediaPlayer.isPlaying()) { mediaPlayer.stop(); } mediaPlayer = MediaPlayer.create(this, Uri.parse(link)); mediaPlayer.start(); 
    • The fact is that I have already tried this and with this option, it gives an error NullPointerException - Sergey
    • This is the way that is needed. No others. NullPointerException arises for a completely different reason and there are 100,500 questions on this topic. Only today there were at least two. - Enikeyschik
    • Nevertheless, I decided my question and there is no error and it works fine - Sergey
    • one
      So wrote, as if decided in some other way: D - Enikeyschik
    • I just tried for a long time to find a solution, and here it is this moment when everything turned out xD! I want to tell everyone! - Sergey
      public void playRadio1() { if(mediaPlayer != null){ if(mediaPlayer.isPlaying()){ mediaPlayer.stop(); mediaPlayer.release(); } } String link1 = "http://ep128.hostingradio.ru:8030/ep128"; mediaPlayer = MediaPlayer.create(this, Uri.parse(link1)); mediaPlayer.start(); }