2017-08-12 63 views
0

将数据插入我的数据库时,我使用-1。我是否应该不使用0来指示是否插入了NOTHING,然后返回false。只是想知道这是正确的方式?将数据插入数据库 - 为什么我使用-1而不是0?

非常感谢,

马克

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;} 

回答

1

按照doc

返回渴望新插入的行的行号,或-1,如果出现错误 发生

所以,你应该使用-1。

那么,为了进一步阐述此API的开发人员,选择-1作为任何发生SQLException的返回值。

欲了解更多信息,请查看source code

还有一件事,你可以使用,而不是两个一个return语句。

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) 
} 
+0

虽然是什么意思?只要阅读文档并理解我应该使用-1但理解为什么? – MarkW

相关问题