Search code examples
androidlistviewarraylisttoast

How do I successfully show my selected listview item in a toast message?


I've been tinkering with some code from udacity.

https://github.com/udacity/ud839_CustomAdapter_Example

I wanted to use my selection from a list in another activity. I usually use a toast message to test if I have successfully selected the correct item etc. But even my toast message is crashing the app.

Below is a shortened version of the arraylist, listview and onitemclicklistener.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create an ArrayList of AndroidFlavor objects
        final ArrayList<AndroidFlavor> androidFlavors = new ArrayList<AndroidFlavor>();
        androidFlavors.add(new AndroidFlavor("Lollipop", "5", R.drawable.lollipop));
        androidFlavors.add(new AndroidFlavor("Nougat", "7", R.drawable.nougat));
        androidFlavors.add(new AndroidFlavor("Oreo", "8", R.drawable.oreo));

        // Create an {@link AndroidFlavorAdapter}, whose data source is a list of
        // {@link AndroidFlavor}s. The adapter knows how to create list item views for each item
        // in the list.
        final AndroidFlavorAdapter flavorAdapter = new AndroidFlavorAdapter(this, androidFlavors);

        // Get a reference to the ListView, and attach the adapter to the listView.
        ListView listView = (ListView)findViewById(R.id.listview_flavor);
        listView.setAdapter(flavorAdapter);

Below is the code that I believe is causing the problem, the onItemClick works if I manually pass strings but it won't pass the selected list item. androidFlavors.get(position) doesn't appear to be correct but I'm unsure why.

    //onClickItemListener to take selected Arraylist component and display the selected component in a toast message
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
            Toast.makeText(getApplicationContext(), (CharSequence) androidFlavors.get(position), Toast.LENGTH_SHORT).show();
        }
    });
}

}


Solution

  • You are trying do you cast new AndroidFlavor("Nougat", "7", R.drawable.nougat) to CharSequence. Instead you should use getVersionName.

    Toast.makeText(getApplicationContext(), androidFlavors.get(position).getVersionName(), Toast.LENGTH_SHORT).show();