Barak
Barak

Reputation: 16393

android SQLite not respecting "not null" constraint

I am working with a simple database. It has three columns. _id (integer primary key autoincrement), jobnumber (text unique not null) and jobpart (text not null).

I am using a dialog with two EditText widgets to get the input and upon button press add it to the database.

When I enter a jobnumber but leave the jobpart empty I would expect that the record would not be added. However, it is being added and I get a blank jobpart. I was using "insert". Looking, I thought perhaps I needed to use "insertWithOnConflict" instead, but that didn't seem to make a difference, the same thing happened.

My next thought was perhaps an empty string did not count as a null value, so I tried the following:

if (jobpart == "") {
    jobpart1 = null;
}else{
    jobpart1 = jobpart;
}

Same thing happened, the database didn't even hiccup and put an empty slot in.

So I started looking through the SQL documentation. I'm wondering if I need to set the db into strict mode, as perhaps an implicit default is being used? Although the section I found that in related to servers, so I'm not sure it even applies here, and if it does, how and when I would do it. (At db creation? On db open?).

Any pointers appreciated.

Upvotes: 1

Views: 705

Answers (2)

tomato
tomato

Reputation: 3383

When you compare strings you need to user the equals() method, not == as String is an object so == just compares pointers.

i.e. You want:

if (jobpart.equals("")) {

Upvotes: 3

Bill Gary
Bill Gary

Reputation: 3005

try this

if (jobpart.matches("")) {
jobpart1 = null;
}else{
jobpart1 = jobpart;
}

or you can make sure they enter something in the edittexts

Upvotes: 2

Related Questions