简体   繁体   中英

My Android ArrayList shows only last added value

I have a ArrayList<String> tokens; to store token values on ListViewClick. after adding values when i retreive the data from ArrayList<String> tokens it shows only the last added value

ArrayList<String> tokens;
...
....
public void onItemClick(AdapterView<?> listView, View view,
                                int position, long id) {
            tokens = new ArrayList<String>();

            Cursor cursor = (Cursor) listView.getItemAtPosition(position);
            String selectedtoken = cursor.getString(cursor.getColumnIndexOrThrow("ContactToken"));

            tokens.add(selectedtoken);
        }
...
...
Log.i("array: ", tokens.toString()); // shows the last added value

Move the statement

tokens = new ArrayList<String>();

out of the onItemClick method preferably into a constructor so its not being re-initialized every time that method is called, eg

public MyClass() {
   tokens = new ArrayList<>();
}

where tokens could be defined as

private List<String> tokens;

You must move the initialization of your ArrayList outside the onItemClick() method. Currently each time you click on an item, you create a new ArrayList

ArrayList<String> tokens = new ArrayList<String>();
...
....
public void onItemClick(AdapterView<?> listView, View view,int position, long id) {

    Cursor cursor = (Cursor) listView.getItemAtPosition(position);
    String selectedtoken = cursor.getString(cursor.getColumnIndexOrThrow("ContactToken"));

    tokens.add(selectedtoken);
}
...
...
Log.i("array: ", tokens.toString()); // shows the last added value

在onCreate()方法中初始化Arraylist

The Problem is, that your try to access your information before tokens is initializied.

You have to move it. For example to the onCreate-Method.

Also possible is to move it to the constructor.

The third way would be to change this:

ArrayList<String> tokens;

to this:

ArrayList<String> tokens= new ArrayList<String>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM