Skip to content Skip to sidebar Skip to footer

How Can I Reduce If-else Statements

My code: if(!''.equals(et1.getText().toString())){ Toast.makeText(getActivity(), 'Please enter text1', Toast.LENGTH_SHORT).show(); } else if(!''.equals(et2.getText().toString())

Solution 1:

Store the objects (et1, 2, 3, ...) in an array, and then iterate on it.

Solution 2:

store it in a List

for (EditText et : etList) {
    if(!"".equals(et.getText().toString()))
}

Solution 3:

You can Add a textwatcher to your fields. see the snippet below.

privateclassGenericTextWatcherimplementsTextWatcher {

    privateGenericTextWatcher() {

    }

    publicvoidafterTextChanged(Editable editable) {

       if(editable.toString().equals(""))
       {
           Toast.makeText(UrActivity.this, "ur toast", Toast.LENGTH_LONG).show();
       }
    }

    publicvoidbeforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    publicvoidonTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }
}

and then register textlistener.

editext.addTextChangedListener(new GenericTextWatcher());

validating it on actual keypress will be faster then clubbing the checking later.

Solution 4:

make one function to check blank and called it once like this...

checkBlank(et1.getText().toString()), 1);
checkBlank(et2.getText().toString()), 2);
checkBlank(et3.getText().toString()), 3);..and so on

here is function..

private void checkBlank(String edt,int pos) {
    // TODO Auto-generated method stubif(edt.equals(""))
    {
        Toast.makeText(getApplicationContext(), "Please enter text"+pos, Toast.LENGTH_SHORT).show();
    }

}

Godd Luck:)

Post a Comment for "How Can I Reduce If-else Statements"