0

I have a case, If my update query is failed due because there is no existing data in database. Then, I want to insert new record if not available already in database. I searched everywhere, But, i did not get a solution according my source code. Find the below code and tell me the solution. Thanks advance dude.

 SQLiteDatabase db = this.getWritableDatabase();
     ContentValues values = new ContentValues();
     values.put(PAGENUM, stepaObj.getPageno());
     values.put(SCORE, stepaObj.getScore());
     values.put(FIR, stepaObj.getFir());
     values.put(PENALTY, stepaObj.getPenalty());
     values.put(PUTTS, stepaObj.getPutts());
     values.put(PLAYED, stepaObj.getPalyed());
     values.put(SCORECARDID, stepaObj.getScorecardid());
     values.put(ISUPDATE, stepaObj.getIsupdate());

     int result = db.update(TABLE_SCORECARD_STEPA, values, SCORECARDID+" = ?",
                new String[] { String.valueOf(scorecardID)});

     System.out.println("updateScore by API data = "+result);

     db.close(); 
iffu
  • 331
  • 1
  • 4
  • 16
Rahul Rawat
  • 999
  • 2
  • 17
  • 40

1 Answers1

4

If the update failed then the result will be 0 ( result : number of rows affected by update)

int result = db.update(TABLE_SCORECARD_STEPA, values, SCORECARDID+" = ?",
            new String[] { String.valueOf(scorecardID)});

if(result <= 0){

     result = db.insert(TABLE_SCORECARD_STEPA, null values);

}
naveejr
  • 735
  • 1
  • 15
  • 31
  • @RahulRawat - Usually db.update(.. ) will replace the record. db.update(..) will fail mostly because the primary key not found in the table. In that case you can insert a new record using db.insert(..). To insert a record you can use db.insertWithOnConflict(...) where you can choose some action when there is a conflict. – naveejr Jun 25 '14 at 10:46