我试图避免使用此代码保存数据库中的空记录,但它也保存空记录

时间:2016-04-29 01:10:42

标签: android

saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            questionStr = String.valueOf(questionET.getText());
            answerOneStr = String.valueOf(ansOneET.getText());
            answerTwoStr = String.valueOf(ansTwoET.getText());
            answerThreeStr = String.valueOf(ansThreeET.getText());
            answerFourStr = String.valueOf(ansFourET.getText());
            correctAnswerStr = String.valueOf(correctAnsET.getText());
            if (questionStr == null || answerOneStr == null || answerTwoStr == null || correctAnswerStr == null) {
                Toast.makeText(getApplicationContext(), "Please Fill Fields ", Toast.LENGTH_SHORT).show();
            } else {
                questionManagerObject.InsertIntoQuestions(questionStr, answerOneStr, answerTwoStr, answerThreeStr, answerFourStr, correctAnswerStr, questionTableSubjectId);
                Toast.makeText(getApplicationContext(), "Question Saved ", Toast.LENGTH_SHORT).show();
            }
        }
    });

这是保存按钮代码...我试图将null更改为空“”但没有更改

3 个答案:

答案 0 :(得分:1)

试试这个方法:

private boolean isEmpty(String str)
{
    if (str == null || str.trim().isEmpty())
    {
        return true;
    }
    return false;
}

然后在您的代码中使用它:

if (isEmpty(questionStr) || isEmpty(answerOneStr) ||  
    isEmpty(answerTwoStr) || isEmpty(answerThreeStr) || 
    isEmpty(answerFourStr) ||isEmpty(correctAnswerStr))
{
   // your code
} 

答案 1 :(得分:0)

使用String.trim()确保它不是空格然后转到条件。

trim whitespace from a string?

答案 2 :(得分:0)

用这个替换你的空检查:

 if (questionStr == null && answerOneStr == null 
             && answerTwoStr == null && correctAnswerStr == null) {
   Toast.makeText(getApplicationContext(), "Please Fill Fields ", Toast.LENGTH_SHORT).show();
}