-1

My task is to get input text in EditText into a toast when I press the button and if there is no text, do nothing, but app crashes whenever I try to open it. Here is my code:

package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    EditText name=(EditText)findViewById(R.id.EditText1);

    public void cLickFuntion(View view){
        String nameString=name.getText().toString();
        Toast.makeText(getApplicationContext(),nameString,Toast.LENGTH_SHORT).show();
    }
}
343intact
  • 1
  • 1
  • Does this answer your question? [Get Value of a Edit Text field](https://stackoverflow.com/questions/4531396/get-value-of-a-edit-text-field) – Ashish May 25 '20 at 15:30
  • 1
    I'm guessing `EditText name=(EditText)findViewById(R.id.EditText1);` this line is causing the crash because you're calling it before the view has been created. – Quinn May 25 '20 at 15:34
  • @Quinn That's true, thank you! – 343intact May 25 '20 at 15:39

1 Answers1

2

Declare EditText as global and change onCreate like below

public class MainActivity extends AppCompatActivity {

    EditText name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name=(EditText)findViewById(R.id.EditText1);

    }

    public void cLickFuntion(View view){
        String nameString=name.getText().toString();
        Toast.makeText(getApplicationContext(),nameString,Toast.LENGTH_SHORT).show();
    }
}
sasikumar
  • 12,540
  • 3
  • 28
  • 48