简体   繁体   中英

Inserting data into database - Why am I using -1 instead of 0?

When inserting data into my database I use -1. Should I not be using 0 indicating if NOTHING is inserted then return false. Just wondering is this the correct way?

Many thanks,

Mark

Routine.java

if (routineInserted) {                                                          

Toast.makeText(RoutineEdit.this, "Activity Inserted", Toast.LENGTH_LONG).show();

MediaPlayer mymedia = MediaPlayer.create(RoutineEdit.this, R.raw.whoosh);
 mymedia.start();

} else {

Database.java

    public boolean insertRoutine(int activityImage, String selectedDay, int activitySlot) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(RoutineColumn1,selectedDay);                                                  
    contentValues.put(RoutineColumn2,activityImage);                                                
    contentValues.put(RoutineColumn3,activitySlot);                                                 
    long result = db.insert(RoutineTable, null, contentValues);                                     // The db.insert is responsible for insertion of the data into the database and stores the result of this action (either true or false) in result.

    if(result == -1)                                                                                // if the result is not equal to -1 or data is not successfully inserted it will return FALSE. otherwise TRUE
        return false;
    else
        return true;}

According to the doc .

Returns long the row ID of the newly inserted row, or -1 if an error occurred

So you should use -1.

Well, to elaborate further developers of this API chose -1 as return value for any occurence SQLException.

For more information you should check source code

One more thing, You can use one return statement instead of two.

    public boolean insertRoutine(int activityImage, String selectedDay, int activitySlot) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(RoutineColumn1,selectedDay);                                                  
        contentValues.put(RoutineColumn2,activityImage);                                                
        contentValues.put(RoutineColumn3,activitySlot);                                                 
        long result = db.insert(RoutineTable, null, contentValues);                                     // The db.insert is responsible for insertion of the data into the database and stores the result of this action (either true or false) in result.

        return (result != -1)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM