-4

Want to get quick answer how to list all items on my listview, in order to print out a list or share to a notepad app etc. That is, to get a variable with following information from the listview: "apple", "banana", "orange". Below is my listview. Thanks

    String[] values = new String[] { "apple", "banana", "orange" };

    listItems = new ArrayList<String>();
    for (int i = 0; i < values.length; ++i) {
        listItems.add(values[i]);
    }

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1,
            listItems);

    // Assign adapter to ListView
    listView.setAdapter(adapter);
user2911996
  • 63
  • 1
  • 2
  • 10
  • your array values have only one item" ? it's a '-' or do you excluded some of your line of codes in your post. – Karthika PB May 05 '15 at 05:06
  • have not learn to do that yet and don't find any article that just do this simple thing on the listview ! – user2911996 May 05 '15 at 05:08
  • @user2911996 what do you mean `share to a notepad app`? – Yuva Raj May 05 '15 at 05:15
  • why do you need this in the first place? it doesn't make sense and you already have access to the listItems, which has everything in your listview, since you passed as an argument to the adapter – appoll May 05 '15 at 05:24
  • I think I may add/remove item at a time to the listview later. But is the listItems I have always the same as what I have in the listview? – user2911996 May 05 '15 at 05:30
  • The answers have all confused my original meaning. And I have revised my question. I can conclude for the time being that listItems is what I need to print out the items on the listview. Just I have to keep public access to it. Thanks – user2911996 May 05 '15 at 05:38
  • add a line System.out.Println("mylist"+listItems); after your forloop. and check this in the log – Karthika PB May 05 '15 at 06:00
  • @KarthikaPB did you see my comment? – Yuva Raj May 05 '15 at 06:07
  • yes yes..the answer is no more there. – Karthika PB May 05 '15 at 06:14
  • @user2911996 I added my answer. Check it out. – Yuva Raj May 05 '15 at 06:34
  • Among the several answers, the adapter.getItem method seems also works. In my case, however, the listItems that I already have may be simpler. thanks – user2911996 May 05 '15 at 07:05

4 Answers4

7

Your question says,

Loop through all items in a listview.

I understand from your code that you want to add the items from String array to ArrayList.

But, you can pass String array directly as a third parameter to your ArrayAdapter.

Look at the suggestions provided by Android studio for ArrayAdapter. You can pass String[] or ArrayList too :

enter image description here

Either you can pass String[] or if you wanted to loop through all String[] items to ArrayList, you can simply do by a single line.

    Collections.addAll(arrayList,values);

arrayList - ArrayList

values - String[]

instead of,

    listItems = new ArrayList<String>();
    for (int i = 0; i < values.length; ++i) {
        listItems.add(values[i]);
    }

And in comment section, you said

I think I may add/remove item at a time to the listView later.

In this case, you can have some button to reload the list to show the old items + added new items or to show the list except the items which you've deleted. I'll add below how you have to achieve it.

Have a button AddMore in your layout and whenever you want to add new items, then do like this

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                arrayList.add("lemon"); // this adds item lemon to arraylist
                arrayList.add("Pomgranete");
                arrayAdapter.notifyDataSetChanged(); // this will refresh the listview and shows the newly added items too
            }
        });

You can delete the item similarly by passing the position of the item in arrayList,

      arrayList.remove(arrayList.get(i)); // i is the position & note arrayList starts from 0

So, by summing up everything, here's the full working code :

public class MainActivity extends AppCompatActivity {

    ListView listView;
    String[] values = {"Apple", "Orange", "Banana"};
    List<String> arrayList;
    Button button;

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

        listView = (ListView)findViewById(R.id.listView);
        button = (Button)findViewById(R.id.button);
        arrayList = new ArrayList<String>();

        Collections.addAll(arrayList,values); // here you're copying all items from String[] to ArrayList

        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList);
        listView.setAdapter(arrayAdapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                arrayList.remove(arrayList.get(2)); // here i remove banana since it's position is two. My ordering of items is different so it removed banana. If i use ordering from your quest, it will remove orange.
                arrayList.add("lemon"); // adding lemon to list
                arrayList.add("Pomgranete"); // adding pomgranete
                arrayAdapter.notifyDataSetChanged(); // this used to refresh the listView
            }
        });

     }
    }

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"  tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ADD MORE"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/button" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/button" />


</RelativeLayout>

Output :

List with pre-defined 3 items and one button to load more items.

enter image description here

List with old 3 items + newly added 2 items (Here i didn't use arrayList.remove)

enter image description here

List with old items except deleted item + newly added 2 items (Here i used arrayList.remove to remove banana by arrayList.remove(arrayList.get(2));)

enter image description here

Yuva Raj
  • 3,881
  • 1
  • 19
  • 30
  • Yes, this is what I want. In your example, arrayList is what I want and I can get the strings inside and put to a variable and share it to other apps using an intent. Just I use other programming language before so don't find out any example doing the same thing. The example is good but it seems not work if there are duplicated items on the listview. try give also another example that works with duplicated items too? Thanks – user2911996 May 05 '15 at 06:54
  • @user2911996 Your question is fully concentrated on how to loop through all items in a listView. I went ahead and even provided example with working code with explanations. Now, if you want other things like to prevent duplicate items, then you need to start new post or look at this post http://stackoverflow.com/questions/14192532/how-to-prevent-the-adding-of-duplicate-objects-to-an-arraylist – Yuva Raj May 05 '15 at 07:04
  • My list may contains duplicated items like a logging of how many apples bought this time and do not want to ensure unique values. But your answer fulfill my needs already. Thanks – user2911996 May 05 '15 at 12:33
0

As I understand you want to create an ArrayAdapter, later add a few items to it and at some point retrieve all items from it, right?

Since you use ArrayAdapter you can just iterate over its content:

    String[] items = new String[adapter.getCount()];
    for(int i = 0; i < adapter.getCount(); i++){
        items[i] = adapter.getItem(i);
        Log.d("TAG", "Item nr: " +i + " "+ adapter.getItem(i));
    }

ArrayAdapter documentation

bryn
  • 291
  • 1
  • 3
  • 5
0

Since you already have an array AND an arraylist in your code it should be easy.

But if you want to loop later and you have only your listview, I believe there is a getter for the adapter in your listview, and if you cast the given adapter to ArrayAdapter, it should then have a getter to the the items you are looking for.

ArrayAdapter<String> adapter = (ArrayAdapter<String>)mListView.getAdapter();
for(int i=0; i<adapter.getCount();i++){
    String item = adapter.getItem(i);
    /*...*/
}
Damien
  • 141
  • 1
  • 6
-1

You don't need to loop or anything just pass the array directly to the adapter.

adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1,
        values);

the new ArrayAdapter took an array as a third parameter.

humazed
  • 74,687
  • 32
  • 99
  • 138
  • Sorry, I miss understanding your question I think you only want to display items in ListView. but I now know you was wanting it to be able to add and delete items. – humazed May 05 '15 at 17:01