Search code examples
javaandroidtextuser-input

Return user input from Android EditText field


I am new to Android dev. and to Programming in general. I have a text based RPG I wrote in Java as a terminal app, and I am trying to recreate it as an Android app; however, I am getting stuck quite at the beginning.

How can I return the user input from an EditText view and store that value in a String?

Below is a throwaway project I made to figure out the problem:

public class MainActivity extends AppCompatActivity {

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

    String a = "Hello from";
    String b = "the other";
    String c = "SIDE!";
    String d = "What you don't like Adele?";

    final String userIn;

    final EditText editText = (EditText) findViewById(R.id.editText);
    TextView textView = (TextView) findViewById(R.id.viewText);

    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                sendMessage();
                handled = true;
            }
            return handled;
        }

        private void sendMessage() {
            userIn = editText.getText().toString();
        }
    });

}

I cannot change the value of userIn because it has to be final to work in the function. I'm sure I'm missing something obvious, but any help would be grand!


Solution

  • Declare userin outside of onCreate() and will work to change it . Check this :

    public class MainActivity extends AppCompatActivity {
    String userIn;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        String a = "Hello from";
        String b = "the other";
        String c = "SIDE!";
        String d = "What you don't like Adele?";
    
    
    
        final EditText editText = (EditText) findViewById(R.id.editText);
        TextView textView = (TextView) findViewById(R.id.viewText);
    
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    sendMessage();
                    handled = true;
                }
                return handled;
            }
    
            private void sendMessage() {
                userIn = editText.getText().toString();
            }
        });
    
    }