Making required EditText field in Android Studio

I am starting to make an app. I currently have one EditText. How do I make it required? When nothing is entered into the EditText! the message Please Enter a username should flash on the screen but it still goes to the next scene/activity. How do I stop the submit if the length is 0. I put return false into the public void but I get the following message cannot return a value from a method with void result type

    public void sendMessage(View view){
    Intent intent = new Intent(this,DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();

    //Trim whitespace
    message = message.trim();

    //Checks if the message has anything.
    if (message.length() == 0)
    {
        editText.setError("Please Enter a username!");
        //return false;
    }
    intent.putExtra(EXTRA_MESSAGE,message);
    startActivity(intent);
}

Solution 1:

try this

string text=editText.getText().toString().trim();
if (TextUtils.isEmpty(text)){
            editText.setError("Please Enter a username!");
        }else {
            //do something
        }

Solution 2:

Instead of return false;, just write return; with no return type (because the method's return type is void) and it should let you leave the method.

Solution 3:

Modify the function like the following.

public void sendMessage(View view){
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();

    //Trim whitespace
    message = message.trim();

    //Checks if the message has anything.
    if (message.length() == 0) {
        editText.setError("Please Enter a username!");
        return;
    }

    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

Solution 4:

Use if and else clause will achieve what you want.

//Checks if the message has anything.
if (message.length() == 0)
{
    editText.setError("Please Enter a username!");
    //return false;
} else {
    intent.putExtra(EXTRA_MESSAGE,message);
    startActivity(intent);
}