Search code examples
androideclipselistviewarraylisttoast

Showing an ArrayList content on a Toast


I have a listView and I want to print the arrrayList which contains the selected items.

I can show the choice that I choose every time. i.e. if I select a choice, I can print it in a toast (I mark it in my code as a comment), but I want to print the whole choices together. Any help please?

Thanks..


Solution

  • If I understand correctly, you want to display the contents of your arrayList in a Toast.

    1. Like donfuxx said, you need to create your arrayList outside of your onclicklistener.
    2. As the user clicks an item, it will be added to your arrayList.
    3. Then loop over the list to fill a string called allItems, then show allItems in a toast.

      ArrayList<String> checked = new ArrayList<String>();
      
      listView.setOnItemClickListener(new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view,
                  int position, long id) {
      
              String listItem = (String) listView.getItemAtPosition(position);
      
              if(!checked.contains(listItem)){ //optional: avoids duplicate Strings in your list
                  checked.add((position+1), listItem);
              }
              String allItems = ""; //used to display in the toast
      
              for(String str : checked){
                allItems = allItems + "\n" + str; //adds a new line between items
              }
      
              Toast.makeText(getApplicationContext(),allItems, Toast.LENGTH_LONG).show();
          }
      });