Akshay Sharma Akshay Sharma - 4 months ago 22
Android Question

Invalid Index is Zero on Playing Song

I am creating a music player app. I have two classes named "Tab3Tracks" and "NowPlaying". In "Tab3Tacks" class, songs are loaded in ListView. So that when someone clicks on a song, it sends position of that song to other class so that other class will able to play that song. But i am getting error while clicking on song. I dont know where i am making mistake. In logcat, i received error "Invalid Index 0, size is 0" in NowPlaying class. I am posting LogCat error code. Check my code for any mistakes. Thanks in advance.

Tab3Tracks Class

public class Tab3Tracks extends ListFragment {


public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}

private ArrayList<String> trackslist = new ArrayList<>();


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab3tracks, container, false);


final String trackid = MediaStore.Audio.Media._ID;
final String trackno = MediaStore.Audio.Media.TRACK;
final String trackname = MediaStore.Audio.Media.TITLE;
final String path = MediaStore.Audio.Media.DATA;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

ContentResolver cr = getContext().getContentResolver();
final String[] projection = {trackid,trackno,trackname,path
};
final Cursor cursor = cr.query(uri,projection,null,null,null);
if (cursor!=null){
if(cursor.moveToFirst()){
do{
int trackIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
trackslist.add(cursor.getString(trackIndex));
}while(cursor.moveToNext());
}
} cursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),R.layout.playlist_item,R.id.songTitle,trackslist
);
setListAdapter(adapter);
return v;
}


public ArrayList<String> getList(){
return trackslist;
}



@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int songIndex = position;

// Starting new intent
Intent in = new Intent(getActivity(), NowPlaying.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
startActivityForResult(in, 100);
getActivity().finish();
}
}


NowPlaying Class

public class NowPlaying extends AppCompatActivity {

public ArrayList<String> songsList = new ArrayList<String>();
public Tab3Tracks tab3tracks;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
// Getting all songs list
tab3tracks = new Tab3Tracks();
songsList= tab3tracks.getList();


// By default play first song
playSong(0);

}



/**
* Receiving song index from playlist view
* and play the song
*/
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
currentSongIndex = data.getExtras().getInt("songIndex");
// play selected song
playSong(currentSongIndex);
}

}

/**
* Function to play a song
*
* @param songIndex - index of song
*/
public void playSong(int songIndex) {
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex));
mp.prepare();
mp.start();
// Displaying Song title
String songTitle = songsList.get(songIndex);
songTitleLabel.setText(songTitle);

// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);

// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);

// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


LogCat Error

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.digital.thefearstuff.tfsmusicplayer/com.digital.thefearstuff.tfsmusicplayer.NowPlaying}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5466)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.digital.thefearstuff.tfsmusicplayer.NowPlaying.playSong(NowPlaying.java:286)
at com.digital.thefearstuff.tfsmusicplayer.NowPlaying.onCreate(NowPlaying.java:83)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)

Answer

Firstly, please avoid asking such questions as Why is this code not working? seeking debug help, since they tend to get a lot of downvotes and are usually quickly closed off. Always try to minimize and isolate your problem. Debug by yourself and see How to create a Minimal, Complete, and Verifiable example for future posts.

Now to question, here in playSong(0) you try to access element at position 0 but the list is empty and there is no such position, therefore IndexOutOfBounds.

    at com.digital.thefearstuff.tfsmusicplayer.NowPlaying.playSong(NowPlaying.java:286)
    at com.digital.thefearstuff.tfsmusicplayer.NowPlaying.onCreate(NowPlaying.java:83)

Your songsList is as it turns out - empty. Which in turn means that trackslist is empty. Which for itself could lead to cursor being null and skipping the add-while-loop. But that you should debug by yourself since you only have the whole code.

To debug it: Add an else and Log with the if (cursor != null){ such as

if (cursor!=null){
    if(cursor.moveToFirst()){
        do{
            int trackIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
            trackslist.add(cursor.getString(trackIndex));
        }while(cursor.moveToNext());
    }
} else {
    Log.d("cursor", "null");
}
cursor.close();

and look for it in the logcat.

Comments