Question

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..

Was it helpful?

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();
        }
    });
    

OTHER TIPS

Well you have the right concept, jsut wrong execution here is the part you missed out on:`

ArrayList<String> checked = new ArrayList<String>();
checked.add((position+1), listItem);
Toast.makeText(getApplicationContext(),checked.get((position+1)), Toast.LENGTH_LONG).show();`

You have to get the position of the element in the ArrayList which you require to fetch, hence checked.get(array position of element here)

If you want to show every item that is in the ArrayList you can use a simple loop and add them to a string like this:

...
checked.add((position+1), listItem);

String tempString = "";
for(int x = 0; x < checked.length(); x++) {
    tempString = tempString + ", " + checked.get(x);
}
tempString = tempString.substring(2);
Toast.makeText(getApplicationContext(),tempString, Toast.LENGTH_LONG).show();

EDIT modified it a bit to only put commas between items

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top