user4093800
user4093800

Reputation:

How to add values to an array on button click in android

Hello everybody I have an edit text and button when I edited some value in edittext on clicking button done, the value need to store in a string array can any one help in fixing of this task ,Thanks in advance

Upvotes: 2

Views: 9214

Answers (3)

MohdTausif
MohdTausif

Reputation: 508

you should use List at place of string array, List is dynamic growing array so you can easily add and remove items from List as below:

List<String> list = new ArrayList<String>();
if(button clicked)
{
   list.add(editText.getText().toString());
}

or if you are bound to use array of string in any case then follow "Kay" solution as well in that case you need to increment in item index in array before adding item into array.

Upvotes: 0

Ajeet
Ajeet

Reputation: 1560

Try Array List. use the following code in your main java

final ArrayList<String> list = new ArrayList<String>();

Button button= (Button) findViewById(R.id.buttonId);
final EditText editText = (EditText) findViewById(R.id.editTextId)
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        list.add(editText.getText().toString());
    }
});

// to get i th element
int i=0;
Log.d("value", list.get(i));

Upvotes: 3

Karan
Karan

Reputation: 2130

Try:

...
int[] arr = new int[];

//listener
onclick()
  {
    arr = arr.addElement(arr,Integer.parseInt(et.getText().toString()));
  }

 }//oncreate end

static int[] addElement(int[] a, int e) {
a  = Arrays.copyOf(a, a.length + 1);
a[a.length - 1] = e;
return a;
} 

Upvotes: 0

Related Questions