New Activity from ListView

I’m working on a music sheet app, and have a bunch of songs in a ListView.

I’m using an onItemClick method, but the problem is, I don’t know how to open an activity depending on what subitem is selected.

The array of songs is uta[], so I can find the specific String with uta[position], but how can I open a specific activity based off of the position that is picked by the user in the ListView?

Answer

You can make a switch/case statement on the String that you fetch with uta[position]

public void onItemClick(AdapterView parent, View v, int position, long id) {
    String value = uta[position].getValue();
    switch(value){
        case "value1":
            Intent intent = new Intent(this, activity1.class); startActivity(intent);
        break;

        case "value2":
            Intent intent = new Intent(this, activity2.class); startActivity(intent);
        break;

        case "value3":
            Intent intent = new Intent(this, activity3.class); startActivity(intent);
        break;
    }
}

Note: switch/case statement on Strings requires JDK 7, see the Oracle documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *