Search code examples
javaandroidandroid-studioandroid-edittextandroid-toast

EditText.getText.toString() is returning empty string


I am trying to recover the text from EditText but when I Toast the string I am getting an empty string.

Here is the code:

view =inflater.inflate(R.layout.fragment_home, container, false);
EditText id=view.findViewById(R.id.busID);
busId=id.getText().toString();
btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(final View view) {
          Toast.makeText(getContext(),busId,Toast.LENGTH_LONG).show();
     }
});

Here is the screenshot

ScreenShot

Please help me out. I don't know why it is returning empty string


Solution

  • You are extracting the String from the EditText too early.

    Change your code like this:

    btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(final View view) {
              busId=id.getText().toString();
              Toast.makeText(getContext(),busId,Toast.LENGTH_LONG).show();
         }
    });