So the form I have written has two fields, a body and a title. I am hoping to get the form to throw a toast message if those fields contain no data to prevent the user from saving it to the database. The code should do one of three things. The first being what I am trying to accomplish above. The second is if the ID intent is null, it will create a new entry, and if the ID intent has content, it will update the database entry with the new content. The problem I am having is when the form fields are null, it still saves. It seems to completely skip over my first IF statement and I cant seem to figure out why. I’ve tried using both null and “” for the first IF statement, both separately and together. Help?
submitBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String titleInsert = titleEdit.getText().toString();
String bodyInsert = bodyEdit.getText().toString();
String dateTimeValue = dateTimeTextView.getText().toString();
if ((titleInsert == null || titleInsert == "") || (bodyInsert == null || bodyInsert == "")){
Context context = getApplicationContext();
CharSequence text = "Please make sure the Title and Body are both filled before saving";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}else if(intentRowId == null){
try{
mDb.open();
mDb.createNote(Integer.parseInt(mIntentId), titleInsert, bodyInsert, dateTimeValue);
finish();
} catch (Exception e) {
e.printStackTrace();
}
} else {
try{
mDb.open();
mDb.updateNote(longRowId, titleInsert, bodyInsert);
finish();
} catch (Exception e){
e.printStackTrace();
Context context = getApplicationContext();
CharSequence text = "SQL Exception Thrown: " + e;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
});
Try
titleInsert.equals("")etc.Additionally, you might want to call
titleInsert = titleInsert.trim();if it is not null, in order to catch blank strings like" ".Edit: if you can use Apache commons lang, you could use the class
StringUtilswhich has aisBlank()method, which returns true if the string is null, empty or only contains whitespace.Edit2:
Short explanation on
titleInsert.equals(""):==normally checks for the very same object, not for the equality datawise. ThustitleInsertand""are not necessarily the same object but might be equal (an empty string). Note that you should useequalsin almost every case when dealing with (non-null) objects, unless you specifically know you want==instead (which is rare, except for checkingobj == null).Short example:
new Long(1) == 1Lis likely to yield false, sincenew Long(1)creates an object different to the Long object which is used for the literal1L(also note that I did exclude auto(un)boxing by using 1L). On the other hand,new Long(1).equals(1L)will yield true.