1

I try to make an App with button which after the push will display all elements from list in editText. But I have a problem, currently after I push the button I see only "second" in editText
In my opinion I need a tips from you about how to do it. Maybe I shouldn't use a loop ?

public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText;
    private ArrayList<String> list = new ArrayList<>();

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

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);

        list.add(0, "first");
        list.add(1, "second");

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

                for (String abc: list){

                    editText.setText(abc);

                }


            }
        });
    }

}

____ edit

public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText;
    private ArrayList<String> list = new ArrayList<>();

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

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);

        list.add(0, "first");
        list.add(1, "second");
        list.add(2, "3");
        list.add(3, "4");
        list.add(4, "5");

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

                String final_text = "";

                for (String abc: list){

                    final_text = final_text + "\n" + abc;

                }

                editText.setText(final_text);

            }
        });
    }

}

enter image description here

2 Answers2

2

You are overwriting the text in editText. Accumulate the strings from the list and do a setText outside the loop:-

@Override
public void onClick(View v) {
  String final_text ="";
  for (String abc: list){
   final_text = final_text +"\n" + abc;
  }
  editText.setText(final_text);
}
Zakir
  • 2,222
  • 21
  • 31
0

On this loop you will always get the last string of the list into the edittext

for (String abc: list){
    editText.setText(abc);
}

You need to create multiple edittext to add multiple value from your list, or else you need to compile all value from list to one string like @Zakir has propose.

TuyenNTA
  • 1,194
  • 1
  • 11
  • 19