0

Everyone, hi! Friends, when you click on the button, a new activity does not start. The following exception occurs: java.lang.ArrayIndexOutOfBoundsException. The log of my error is presented below:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.projectMP3, PID: 3228
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.projectMP3/com.example.projectMP3.Activity.PlayerActivity}: java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2458)
        at android.app.ActivityThread.access$900(ActivityThread.java:172)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5598)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
        at java.util.ArrayList.get(ArrayList.java:310)
        at com.example.projectMP3.Activity.PlayerActivity.getIntentMethod(PlayerActivity.java:167)
        at com.example.projectMP3.Activity.PlayerActivity.onCreate(PlayerActivity.java:62)
        at android.app.Activity.performCreate(Activity.java:5459)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2458) 
        at android.app.ActivityThread.access$900(ActivityThread.java:172) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:146) 
        at android.app.ActivityThread.main(ActivityThread.java:5598) 
        at java.lang.reflect.Method.invokeNative(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:515) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
        at dalvik.system.NativeStart.main(Native Method) 

Program code for MainActivity.java

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
 //....
 private void int_viewPager() {

        ViewPager viewPager;
        TabLayout tabLayout;
        FloatingActionButton openMusicPlayer;
        //...
        androidx.appcompat.widget.Toolbar toolbar;
        viewPager = findViewById(R.id.view_Pager);
        tabLayout = findViewById(R.id.tab_layout);
        //...
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);

        openMusicPlayer = findViewById(R.id.open_Music);
        openMusicPlayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
                startActivity(intent);
            }
        });

    }
}

Program code for PlayerActivity.java:

//...
public class PlayerActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener {
   
    /** Логические переменные (случайное воспроизведение, повтор аудиозаписи) */
    static boolean shuffleBoolean = false, repeatBoolean;
    /** Список музыкальных композиций */
    ArrayList<MusicFile> listSong = new ArrayList<>();
    /** Специальный идентификатор */
    Uri uri;
    /** Обработчик потока - обновляет сведения о времени */
    Handler handler = new Handler();
    /** Потоки воспроизведения */
    Thread playThread, prevThread, nextThread;

    private int position = -1;
    private FloatingActionButton playPause;
    //...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Размещает пользовательский интерфейс на экране активности
        setContentView(R.layout.activity_player);
        // Инициализирует элементы управления
        initView();
        // Получает данные из Intent
        getIntentMethod();

        /* Добавляем listener, который получит
        *  уведомление, когда проигрывание закончится. */
        mediaPlayer.setOnCompletionListener(this);

        //...

        // Перемещение функциональности в фоновый режим
        PlayerActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
               //...
        });  
    }

  
    /** Получает данные из намерения (Intent) */
    private void getIntentMethod() {
        /* Получаем данные, добавленные ранее
        *  с помощью putExtra() */
        position = getIntent().getIntExtra("position", -1);
        String sender =  getIntent().getStringExtra("Sender");

        if(sender!= null && sender.equals("albumDetails")) {
            listSong = album_Music;
        } else {
            listSong = musicFilesSongAdapter;
        }

        if (listSong != null) {
            playPause.setImageResource(R.drawable.ic_pause);
            uri = Uri.parse(listSong.get(position).getPath());
        }

        if (mediaPlayer != null) {
            mediaPlayer.stop();
            // Освобождаем приобретенные ресурсы (память, кодеки)
            mediaPlayer.release();
        }
        mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
        mediaPlayer.start();
        songSeekBar.setMax(mediaPlayer.getDuration() / 1000);
        metaData(uri);
    }

    // Получаем метаданные (альбом и др.)
    private void metaData(Uri uri) {
       //...
    }
 
    private void prevThreadBtn() {
        prevThread = new Thread() {
            @Override
            public void run() {
                super.run();
                playPrev.setOnClickListener(v -> prevBtnClicked());
            }
        };
        prevThread.start();
    }

    /** Обрабатывает нажатие кнопки (Play previous)*/
    private void prevBtnClicked() {
        if (mediaPlayer.isPlaying()) {
            /* Останавливаем воспроизведение,
            * освобождаем ресурсы, связанные с этим объектом */
            mediaPlayer.stop();
            mediaPlayer.release();

            /* Проверяем, включены ли режимы Shuffle, Repeat */
            if (shuffleBoolean && !repeatBoolean) {
                position = getRandom(listSong.size() - 1);
            } else if (!shuffleBoolean && !repeatBoolean) {
                position = ((position - 1) < 0 ? (listSong.size() - 1) : (position - 1));
            }

            uri = Uri.parse(listSong.get(position).getPath());
            // Создаем MediaPlayer для заданного URI
            mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
            // Устанавливаем метаданные
            metaData(uri);
            //...
  }

    /** Вызывается после возобновления активности
     *  (after onResume() has been called) */
    @Override
    protected void onPostResume() {
        playThreadBtn();
        prevThreadBtn();
        nextThreadBtn();
        super.onPostResume();
    }


    /** Получает ссылки элементов управления */
    private void initView() {
        songName = findViewById(R.id.song_name);
        durationPlayed = findViewById(R.id.duration_played);
        totalDuration = findViewById(R.id.duration_total);
        //...
    }

   
    @Override
    public void onCompletion(MediaPlayer mp) {
       //...
    }
}

If I understand correctly, then the error is in the following lines:

if (listSong != null) {
            playPause.setImageResource(R.drawable.ic_pause);
            uri = Uri.parse(listSong.get(position).getPath());
        }

But... I do not know how to fix the error. Could you help?

MAGistr
  • 3
  • 3
  • 1
    *Caused by: java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1* makes me think your `private int position = -1` might be responsible for this `Exception`… Maybe you get the default value from the `Intent` at `position = getIntent().getIntExtra("position", -1);`. – deHaar Apr 21 '22 at 11:07

2 Answers2

1

it is because your position is -1, you must check

if(position != -1)
    uri = Uri.parse(listSong.get(position).getPath());

you have not send position when starting activity

Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
startActivity(intent);
  • This is very likely to be the cause, @MAGistr. You have defined `-1` as default value if the `Intent` received in `PlayerActivity` does not contain the extra `"position"`, which it doesn't because you haven't attached it in the `MainActivity`. – deHaar Apr 21 '22 at 11:21
  • If I understand you correctly, my program code should look like this: ```if (listSong != null) { playPause.setImageResource(R.drawable.ic_pause); if(position != -1) uri = Uri.parse(listSong.get(position).getPath()); }``` – MAGistr Apr 21 '22 at 12:03
  • @FrenyChristian check out my comment. – MAGistr Apr 21 '22 at 12:15
  • @MAGistr its also depend on your requirement, you can also set default position to 0, in that case if intent does not send any value, it will play first item from your list. private int position = 0; – Freny Christian Apr 21 '22 at 12:25
0
private int position = -1;

This is causing your ArrayIndexOutOfBound

Lukas Novicky
  • 921
  • 1
  • 19
  • 44