Reputation: 433
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
Upvotes: 1
Views: 727
Reputation: 1651
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>();
Upvotes: 0
Reputation: 159754
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, e.g.
public MyClass() {
tokens = new ArrayList<>();
}
where tokens
could be defined as
private List<String> tokens;
Upvotes: 5
Reputation: 11969
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
Upvotes: 5