我正在建立一个数据库,我想防止用户输入空文本。我该怎么办?下面的代码有什么问题?
public void AddData () {
addbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (name != null && surname != null && marks != null) {
String name1 = name.getText().toString();
String surname1 = surname.getText().toString();
String marks1 = marks.getText().toString();
boolean isInserted = mydb.insertdata(name1, surname1, marks1);
if (isInserted) {
Toast.makeText(MainActivity.this, "Data entered successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Failed to enter Data", Toast.LENGTH_LONG).show();
}
}else if (name == null && surname == null && marks == null) {
Toast.makeText(MainActivity.this, "Please enter Data", Toast.LENGTH_LONG).show();
}
}
});
}
答案 0 :(得分:0)
您只想检查字符串的长度。
public void AddData () {
addbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name1 = name.getText().toString();
String surname1 = surname.getText().toString();
String marks1 = marks.getText().toString();
if (name1.length() > 0 && surname1.length() > 0 && marks.length() > 0) {
boolean isInserted = mydb.insertdata(name1, surname1, marks1);
if (isInserted) {
Toast.makeText(MainActivity.this, "Data entered successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Failed to enter Data", Toast.LENGTH_LONG).show();
}
}else if (name == null && surname == null && marks == null) {
Toast.makeText(MainActivity.this, "Please enter Data", Toast.LENGTH_LONG).show();
}
}
});
}
您还可以编写一个函数来为您验证输入内容
private boolean validateInput(String input) {
if(input == null)
return false;
if( input.length == 0)
return false;
//... Other validation checks
return true;
}
但是您不只是想根据长度来验证数据。输入验证应反映您期望的数据类型。例如,如果您要查找电话号码,则应删除不属于电话号码的所有字符。您不希望有人在您的电话号码输入字段中输入他们的电子邮件地址。
答案 1 :(得分:0)
我们考虑使用Guava library和方法isNullOrEmpty,它非常有用。