1

I've difficulty in creating a validation before saving it to , below is the code:

public void save(View v){
    String weight = weightinputid.getText().toString();
    String bmi = BMIfinal.getText().toString();
    String status = BMIStatus.getText().toString();


    long id = data.insertData(weight, bmi, status);

    if(id<0){
        message.mess(this, "Error");
    }
    else{
        message.mess(this, "BMI has been saved");
    }
}

How do I create a validation if all the textfields are empty? my problem right now, even if i pressed the save button, the empty textfields was saved inside the database

Abhishek
  • 2,925
  • 4
  • 34
  • 59
chase
  • 65
  • 4

2 Answers2

1

You can just try this, to check if value is not entered in the EditText.

if (weight .equals(""))
{
   Toast.makeText(getApplicationContext(),"Please enter Value1", Toast.LENGTH_LONG).show();
}
if (bmi.equals(""))
{
   Toast.makeText(getApplicationContext(),"Please enter Value2", Toast.LENGTH_LONG).show();
}
if (status.equals(""))
{
   Toast.makeText(getApplicationContext(),"Please enter Value3", Toast.LENGTH_LONG).show();
}

Alternatively, you can use .matches("") instead of .equals("")

UPDATE

As @Rajesh mentioned in his comments, you can also use

TextUtils.isEmpty(weightinputid.getText())

to achieve the same functionality.

Lal
  • 14,726
  • 4
  • 45
  • 70
0

You can definitely do @Lal suggestion but in case the N fields are empty it's going to show the N toasts, and that's not very useful:

I'll suggest to do the following one of the following options:

a) Implement MaterialEditText: Check the details here: https://github.com/rengwuxian/MaterialEditText

<com.rengwuxian.materialedittext.MaterialEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Min Characters"
        app:met_minCharacters="1" />

b) Use a TextWatcher and enable the SaveButton only after you have your required fields with values: http://developer.android.com/reference/android/text/TextWatcher.html You can see how to it with the following question: Disable Button when Edit Text Fields empty

Community
  • 1
  • 1
moxi
  • 1,390
  • 20
  • 21