I am using an ArrayList
within my code which gets populated by a EditText
field but I am wanting to limit the ArrayList
so it can only hold 10 values. After 10 values have been added if another tries to get added I just need it to not add into the Array
. Anyone got any ideas how to do that?
private static ArrayList<String> playerList = new ArrayList<String>();
Since ArrayList in Java is backed by a built-in array, the limit on the size is equal the same as the limit on the size of an array, i.e. 2147483647.
you can handle it by yourself in getCount() method. you can put a integer in your adapter class and by each click on more button increase it 1.
A list can hold 1000 elements(as per the limit).
trimToSize() method is used for memory optimization. It trims the capacity of ArrayList to the current list size. For e.g. An arraylist is having capacity of 15 but there are only 5 elements in it, calling trimToSize() method on this ArrayList would change the capacity from 15 to 5.
In your handler method:
if(playerList.size() < 10) {
// playerList.add
} else {
// do nothing
}
Edit: Your mistake is here:
if(playerList.size() < 10) {
Button confirm = (Button) findViewById(R.id.add);
confirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText playername = (EditText) findViewById(R.id.userinput);
playerList.add(playername.getText().toString());
adapter.notifyDataSetChanged();
playername.setText("");
}});
} else {
// do nothing
}
You should check the size inside the onClickListener
, not outside:
Button confirm = (Button) findViewById(R.id.add);
confirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText playername = (EditText) findViewById(R.id.userinput);
if(playerList.size() < 10) {
playerList.add(playername.getText().toString());
adapter.notifyDataSetChanged();
playername.setText("");
} else {
// do nothing
}
}
});
If you don't have control over the function that adds elements to the list, you might want to override the ArrayList
add
.
public class MySizeLimitedArrayList extends ArrayList<Object> {
@Override
public boolean add(Object e) {
if (this.size() < 10) {
return super.add(e);
}
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With