editText field is required before moving on to another Activity

Viewed 103100

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.

7 Answers

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;
}

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);
}

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;
                }
            }
        });
    }
}
Related