【问题标题】:Validation for save button验证保存按钮
【发布时间】:2015-09-14 03:08:37
【问题描述】:

在将验证保存到 之前,我很难创建验证,下面是代码:

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

如果所有文本字段都为空,我如何创建验证?我现在的问题,即使我按下保存按钮,空文本字段也保存在数据库中

【问题讨论】:

    标签: sqlite android database sqlite validation save


    【解决方案1】:

    你可以试试这个,检查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();
    }
    

    或者,您可以使用 .matches("") 代替 .equals("")

    更新

    正如@Rajesh 在他的 cmets 中提到的,您也可以使用

    TextUtils.isEmpty(weightinputid.getText())
    

    实现相同的功能。

    【讨论】:

    • 你也可以使用 weight.isEmpty() 代替 weight.equals()。
    • @RajeshJadav 那么应该是TextUtils.isEmpty(weightinputid.getText())
    【解决方案2】:

    您绝对可以执行@Lal 建议,但如果 N 个字段为空,它将显示 N 个 toast,这不是很有用:

    我建议执行以下选项之一:

    a) 实现MaterialEditText: 在此处查看详细信息: 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) 使用 TextWatcher 并仅在您拥有带有值的必填字段后启用 SaveButton: http://developer.android.com/reference/android/text/TextWatcher.html 您可以通过以下问题了解如何操作: Disable Button when Edit Text Fields empty

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-26
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      相关资源
      最近更新 更多