android check duplicate values before inserting data into database

拈花ヽ惹草 提交于 2020-01-22 02:55:29

问题


    String new_recorded_lastname="a lastname";
    ////record to database......
    Cursor cursor = db.rawQuery("SELECT lastname FROM people; ",null);

     if (cursor != null){
  while(cursor.moveToNext()){

    String recorded_lastname=cursor.getString(cursor.getColumnIndex("lastname"));
    if(!(recorded_lastname.equals(new_recorded_lastname))){ 
    //add new_recorded_lastname to database
    break;
    }
    }
    }

I want to have a lastname only once in my database. Even though I check with "if(!(recorded_lastname.equals(new_recorded_lastname)))" this line code to, it adds same records again and again. How can I control a lastname to add only once?

//It works for the first record very well, but starting from the second record, it adds some lastname again and again....


回答1:


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.



来源:https://stackoverflow.com/questions/10658513/android-check-duplicate-values-before-inserting-data-into-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!