android check duplicate values before inserting data into database

前端 未结 1 1650
走了就别回头了
走了就别回头了 2021-01-28 13:13
    String new_recorded_lastname=\"a lastname\";
    ////record to database......
    Cursor cursor = db.rawQuery(\"SELECT lastname FROM people; \",null);

     if (curs         


        
相关标签:
1条回答
  • 2021-01-28 13:42

    It seems to me that you are checking every record in the database, and as soon as you find one that does not contain the given lastname you add the record to the database. You should accumulate the results of the checks, something like this:

    boolean lastnamePresent = false;
    while(cursor.moveToNext()){
        String recorded_lastname=cursor.getString(cursor.getColumnIndex("lastname"));
        if(recorded_lastname.equals(new_recorded_lastname)){ 
            lastnamePresent = true;
            break;
        }
    }
    
    if(!lastnamePresent)
        // add new_record_lastname to database
    

    Though it would sure be better if you use SQLite tools to handle this kind of stuff. Like setting the column to UNIQUE.

    0 讨论(0)
提交回复
热议问题