32

I have validation for editText. If the editText field is empty it should fail validation and stop the user moving on to another Activity, as a value is required. How to do it? I know this is a basic question, but I can't figure out how to do this.

My code:

btninsert = (Button)findViewById(R.id.btn_insert);
btninsert.setOnClickListener( new View.OnClickListener() {
    public void onClick(View v) {
        insertValues();
        EditText userName = (EditText) findViewById(R.id.editText1);

        if( userName.getText().toString().length() == 0 )
            userName.setError( "First name is required!" );

        Intent i = new Intent(getApplicationContext(), Login.class);
        startActivity(i);
    }
});

When this Button is clicked the user is redirect to next screen, but I need that if validation fails they stay on the current Activity, and only when validation is successful (i.e. a value has been entered) they go to the next Activity.

Chilledrat
  • 2,593
  • 3
  • 28
  • 38
Krishna Veni
  • 2,217
  • 8
  • 27
  • 53

8 Answers8

80

It's easy...check if your EditText is empty as in below example below.

if( TextUtils.isEmpty(userName.getText())){
   /**
    *   You can Toast a message here that the Username is Empty    
    **/
    
   userName.setError( "First name is required!" );

}else{
   Intent i = new Intent(getApplicationContext(), Login.class);
   startActivity(i);
}

Here is a Kotlin version:

userName.takeIf { it.isEmpty() }?.let {
  userName.error = "First name is required!"
} ?: run {
   startActivity(Intent(applicationContext, this))
}
Haresh Chaudhary
  • 4,390
  • 1
  • 34
  • 57
8

Try this:

bt.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0)
    {
        String  str=et.getText().toString();

        if(str.equalsIgnoreCase(""))
        {
            et.setHint("please enter username");//it gives user to hint
            et.setError("please enter username");//it gives user to info message //use any one //
        }
        else
        {
            Intent in=new Intent(getApplicationContext(),second.class);
            startActivity(in);
        }
    }
});
Chilledrat
  • 2,593
  • 3
  • 28
  • 38
Rajender Reddy
  • 447
  • 2
  • 4
  • 8
5

You can also try this:

 if ( ( userName.getText().toString().trim().equals("")) ) 
 {
      Toast.makeText(getApplicationContext(), "User name is empty", Toast.LENGTH_SHORT).show();
 }
 else
 {
      Intent i = new Intent(getApplicationContext(), Login.class);
      startActivity(i);
 }
fidazik
  • 423
  • 1
  • 5
  • 11
3

I faced a similiar problem. In my case, I had a lot of Edittexts to verify, some them was child of another layouts. Tip: all views must be in same root view. So, to be simple:

...
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.viewGroup);
checkFieldsRequired(viewGroup);
...

public boolean checkFieldsRequired(ViewGroup viewGroup){

    int count = viewGroup.getChildCount();
    for (int i = 0; i < count; i++) {
        View view = viewGroup.getChildAt(i);
        if (view instanceof ViewGroup)
            checkFieldsRequired((ViewGroup) view);
        else if (view instanceof EditText) {
            EditText edittext = (EditText) view;
            if (edittext.getText().toString().trim().equals("")) {                  
                edittext.setError("Required!");                 
            }
        }
    }

    return false;
}
Leonardo Costa
  • 994
  • 11
  • 26
3

I understand it's an old question but may this helps, you can use .isEmpty() instead of .equals()

if( userName.getText().toString().isEmpty()){

   /**
    *   You can Toast a message here that the Username is Empty    
    **/

   userName.setError( "First name is required!" );

}else{
   Intent i = new Intent(getApplicationContext(), Login.class);
   startActivity(i);
}
XIII
  • 2,036
  • 16
  • 25
2

Better to test empty textField using If condition for all required or special validation cases and setError to focus.

If(txtName.getText().toString().trim().equals(""))
{
//Your message or any other validation
}
Akshay Mishra
  • 1,535
  • 2
  • 15
  • 14
0

I know this is an old post, but I needed similar functionality in my application, so I deciced to develop a simple but powerful validator for ease of re-use.

link for github repo It's super easy to use.

  1. Create a list of the fields you want to be mandatory
  2. Call validateViewFields method and pass the list of views

code example for Activity:

    public class AddContractActivity extends AppCompatActivity {

    TextView contractDescriptionTextView;
    TextView totalAmountTextView;

    List<View> fieldsToBeValidated;

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

        contractDescriptionTextView = findViewById(R.id.contractDescriptionEditText);
        totalAmountTextView = findViewById(R.id.totalAmountText);

        fieldsToBeValidated = new ArrayList<>(Arrays.asList(
                contractDescriptionTextView,
                totalAmountTextView));

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UIValidator.validateViewFields(fieldsToBeValidated, true)) {
                    Toast.makeText(AddContractActivity.this, "Missing Fields", Toast.LENGTH_SHORT).show();
                    mainScrollView.post(new Runnable() {
                        @Override
                        public void run() {
                            mainScrollView.smoothScrollTo(0, 0);
                        }
                    });
                    return;
                }
            }
        });
    }
}
Omar Gharra
  • 21
  • 1
  • 2
0

activity.xml

 <com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textLayoutProductName"
    style="@style/textInputLayout"
    app:boxStrokeColor="#ad5933"
    app:hintTextColor="#ad5933">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edTextProductName"
        style="@style/textInputEditText"
        android:hint="@string/product_name"
        android:maxLength="25" />
</com.google.android.material.textfield.TextInputLayout>

style.xml

<style name="textInputLayout" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_marginTop">@dimen/_5sdp</item>
    <item name="android:layout_marginLeft">@dimen/_10sdp</item>
    <item name="android:layout_marginRight">@dimen/_10sdp</item>
</style>

<style name="textInputEditText">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:maxLength">10</item>
    <item name="android:maxLines">1</item>
    <item name="android:inputType">text</item>
</style>

Activity.kt

val btnAppProduct: Button = findViewById(R.id.btnAddProduct)
val edTextProductName: TextInputEditText = findViewById(R.id.edTextProductName)
val textLayoutProductName: TextInputLayout = findViewById(R.id.textLayoutProductName)

btnAppProduct.setOnClickListener 
 {
    if (Utils().textViewEmptyChecker(textLayoutProductName,edTextProductName, "Product Name is Empty").isNotEmpty()) 
                    { //Your code here }
 }

class Utils.kt

class Utils {
fun textViewEmptyChecker(textInputLayout: TextInputLayout,
        textInputEditText: TextInputEditText,errorMsg: String): String 
        {
            if (textInputEditText.text.toString().isEmpty()) {
                textInputLayout.error = errorMsg
                textInputEditText.isFocusable = true
                textInputEditText.requestFocus()
                return ""
            }
        textInputLayout.error = null
        return textInputEditText.text.toString()
    }
}
Ashfaque
  • 179
  • 4