开发者

code not validating for null values

I have written the below code to validate the value in the string before saving it to the database.

EditText editText2 = (EditText) this.findViewById(R.id.editText1);
           setTime = editText2.getText().toString(); 

           Log.d(setTime, "This is the setTime value");

           if(setTime == null)
           {
               Toast.makeText(Settings.this, "Time cannot be NULL", Toast.LENGTH_LONG).show(); 
           }

           else if(setTime != null)
           {
               cv.put(DatabaseHelper.TIME, setTime);
               db.insert("finalP", DatabaseHelper.TIME, cv);
               db.close();

               editText2.setText("");

               Toast.makeText(Settings.this, "Time saved", Toast.LENGTH_LONG).show();
           }

But even if "setTime" contains the null value, the "if" part is getting skipped and the control goes into the "else" part directly and saving the null value in database.

Isn't this the correct way to valida开发者_如何学Cte??


I think you string is empty not null. So add check for string length too to if clause.

EditText editText2 = (EditText) this.findViewById(R.id.editText1);
setTime = editText2.getText().toString(); 

Log.d(setTime, "This is the setTime value");

if(setTime == null || setTime.length() == 0) {
   Toast.makeText(Settings.this, "Time cannot be NULL", Toast.LENGTH_LONG).show(); 
} else {
   cv.put(DatabaseHelper.TIME, setTime);
   db.insert("finalP", DatabaseHelper.TIME, cv);
   db.close();

   editText2.setText("");

   Toast.makeText(Settings.this, "Time saved", Toast.LENGTH_LONG).show();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜