0
    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....

2
  • 1
    Is there a chance to modify the database field and set it to unique so the database will do all the magic for you? Commented May 18, 2012 at 19:20
  • yes, i can modify the database, so if I do like that, it will be ok? if(!(recorded_lastname.equals(new_recorded_lastname))){ try {//add new_recorded_lastname to database }catch(Exception e){///}break; } Commented May 18, 2012 at 20:06

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

if i use UNIQUE, do I need to check as you explain it, again ?
If you use UNIQUE then you will get an error when trying to INSERT a duplicated last name. How to behave to such error depends on your application logic.
"if(!lastnamePresent)" should be if(lastnamePresent), Am I right ?
Have a look at the insert and insertOrThrow documentation. The first one will return -1 the latter a proper Exception if something's happening (like violtion of unique constrain.). I'd prefer the latter one because in general it doesn't matter whether you compare against -1 or catch an exception. developer.android.com/reference/android/database/sqlite/…
That depends, do you want to add a record if the lastname is already present or if its not?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.