I'm trying to use sqlite trigger before inserting concept for validation in android studio. I'm using 3 fields - farmer_id, farmer_name, father_name and if farmer_name is empty am trying to show an error message as "Farmer Name is mandatory". So I used trigger coding as below in android studio
String farmer_insert_trigger = "CREATE TRIGGER insert_validation"
"BEFORE INSERT on farmer_det"
"BEGIN SELECT CASE WHEN new.farmer_name IS '' THEN"
"RAISE(ABORT,'Farmer Name is mandatory')"
"end;"
"end;";
public void createTriggers() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(farmer_insert_trigger);
}
when I hit "Submit" button to show the error message as "Farmer Name is mandatory" am getting the error message as "near "SELECT":syntax error (code 1);, while compliling CREATE Triger...". Below is my button click event.
btn.setOnClickListener(v->{
String farmerID = farmer_id.getText().toString();
String farmerName = farmer_name.getText().toString();
String fatherName = father_name.getText().toString();
try {
// Execute insert function
dbHandler.createTriggers();
} catch (SQLiteConstraintException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// Just in case the above doesn't catch it
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Did I missed any syntax while creating trigger.
CodePudding user response:
I believe that you are missing spaces where they are required/needed.
Try :-
String farmer_insert_trigger = "CREATE TRIGGER insert_validation /*SPACE*/"
"BEFORE INSERT on farmer_det /*SPACE*/"
"BEGIN SELECT CASE WHEN new.farmer_name IS '' THEN /*SPACE*/"
"RAISE(ABORT,'Farmer Name is mandatory')"
"end;"
"end;";
- Obviously comments
/*SPACE*/
not needed.
CodePudding user response:
You can check if a String is empty from program directly like this :
btn.setOnClickListener(v->{
String farmerID = farmer_id.getText().toString();
String farmerName = farmer_name.getText().toString();
String fatherName = father_name.getText().toString();
if (farmerName.equals("")) {
Toast.makeText(getApplicationContext(), "Farmer Name is mandatory", Toast.LENGTH_LONG).show();
} else {
// Execute insert function
}
});
The program can compile faster because you don't need to check the database and the code is simpler.