How to show a Toast Error Message for an entry to EditText? [SOLVED] – Android Studio


You may have an EditText in your app to take some input from your user for a variety of reasons.
But it should be configured properly to handle problematic data.

For example, if you want the user to enter a number, then you should check whether the data entered in the EditText is a number or not.
In case the data entered fails your check then you should show an error message telling the user about the problem.
This process is also known as input validation.

The best method I have found to do that is using a Toast Notification which pops up on the lower half of the screen with a dark background for a short time telling the error message.
NOTE: This method is no longer the recommended method but still used by a lot of developers.

In the below code I show you how to show a Toast notification error, if the input is empty

if (inputtext.getText().toString()==null || inputtext.getText().toString().trim().equals("")){
                    Toast.makeText(getBaseContext(),"Input Field is Empty", Toast.LENGTH_LONG).show();
                }
                else{
                //do what you want with the entered text
                }

where, inputtext is an object of EditText type.
You will need to declare it(inside onCreate () in most of the cases) as follows:

EditText inputtext= (EditText)findViewById(R.id.edittext);

So basically, Toast.makeText(getBaseContext(),"Your message", Toast.LENGTH_LONG).show(); will generate the toast message and if you want to it to be displayed for some particular case, then just put the condition inside the if statement.

[wpedon id="7041" align="center"]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.