Home > Enterprise >  Android How to save a String from edittext into an array?
Android How to save a String from edittext into an array?

Time:07-02

package com.example.addarray;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    Button button;
    EditText editText;
    int mCounter = 0;
    TextView textView;
    TextView textView2;
    TextView textView3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        button.setOnClickListener(view -> {
            mCounter  ;
            textView = findViewById(R.id.textView1);
            textView.setText(Integer.toString(mCounter));
            textView2 = findViewById(R.id.textView2);
            editText = findViewById(R.id.editText);

            String [] string = new String[mCounter];
            for(int i =mCounter-1; i>mCounter; i  ){
                string[i] = editText.getText().toString();
            }

            textView2.setText(Arrays.toString(string));
        
            textView3 = findViewById(R.id.textView3);
            textView3.setText(editText.getText().toString());
        });
    }
}

I would like to add the input from the edit text into an array upon each click of the button, however, the element of the array only displayed null as shown in the picture. Is there any way to fix it? Thank you.

Output of the program

CodePudding user response:

You create a new array with each click. No need to create a new array on every click. It is possible to save new values in ArrayList.

public class MainActivity extends AppCompatActivity {
    private ArrayList<String> list = new ArrayList<String>();
    // *******
    button.setOnClickListener(view -> {
        // *******
        list.add(editText.getText().toString());
        // ******
    }
 }
  • Related