0

Why does it give only last element, not array of elements?

One.java ArrayList<String> mStringList = new ArrayList<>(); private String block; public ArrayList<String> getList(){ mStringList.add(block); return mStringList; } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { //some code , TextView present inside ListView block = textView.getText().toString(); } } Two.java Private One one; ArrayList<String> list = one.getList(); String[] mStringArray = new String[list.size()]; for(int i=0; i< list.size();i++){ mStringArray[i] = list.get(i); } The "list" size is 1 and it gives last element. When I click the button it takes the text and gives it. if I click the button multiple times it gives the text from last element. How do I get all the texts, if button is clicked multiple times?

5th Jun 2019, 2:59 PM
Ghost rider
1 Answer
+ 1
Instead of adding the string to the ArrayList in the getList method, you should add it in the onClick overload. This is because block's state is changed with every click but these changes get discarded as no call to getList is made and the block's value is not saved in the ArrayList. So in the onClick override, before assigning block with a new value, add the existing value to the ArrayList: @Override public void onClick(final View view) { mStringList.add(block); block = textView.getText().toString(); }
5th Jun 2019, 3:38 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar