Display list based on number of items inputted (android)

My goal is to display items based on the inputted value of the user.
for example: the user input is 5.. in my application, items will be listed.

here is my code in MainActivity

public class MainActivity extends AppCompatActivity {
    ArrayAdapter<String> adapter;
    ArrayList<String> itemList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    itemList = new ArrayList<String>();
    adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.txtview, this.itemList);

    ListView listView = (ListView)findViewById(R.id.textView2);
    listView.setAdapter(adapter);

    final EditText editText = (EditText)findViewById(R.id.inputText);
    Button buttonLoadItem = (Button)findViewById(R.id.buttonLoadItems);
    buttonLoadItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String itemAdded;
            try {
                String editTextString = editText.getText().toString();
                final int editTextInteger = Integer.parseInt(editTextString);
                    for (int i = 0; i < editTextInteger; i++) {
                        itemAdded = Integer.toString(i);
                        itemList.add(itemAdded);
                        adapter.notifyDataSetChanged();
                        System.out.println("Item: " + i);
                    }

                } catch (NumberFormatException nbe) {
                Toast.makeText(getApplicationContext(), "Error.", Toast.LENGTH_LONG).show();
                }
        }
    });
}

}

in my onClick method, everytime i click on it, it should display
0
1
2
3
4

i have the for loop for that but in my current implementation, it will only display the first item in the list. What is wrong with my code.?


Source: android

Leave a Reply