androidbuttonandroid-edittexttoastfindviewbyid

Small problem when taking information from a field and showing it in a message in the Android


You can see that I created this simple screen on Android: enter image description here

Code:

public class MainActivity extends AppCompatActivity {

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

    EditText identifier = findViewById(R.id.identifier);
    Button button = findViewById(R.id.button);

    String identifierIntoString = identifier.getText().toString().trim();

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), identifierIntoString, Toast.LENGTH_LONG).show();
        }
    });
} 

}

Please, what to do so that when a user types something in the field, and then clicks on the button, it appears what the user typed to the Toast.makeText?


Solution

  • Make changes as per below.

        button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String identifierIntoString = identifier.getText().toString().trim();
            Toast.makeText(getApplicationContext(), identifierIntoString, Toast.LENGTH_LONG).show();
        }
    });