Eric Cheng
Eric Cheng

Reputation: 21

The sqlite database insert duplicated data

I got the data from webservice and insert them to database in activity onCreate() function. the code is as below:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.contact_person);

    RunningService runningService = new RunningService();
    runningService.insert(staff);
    initView();
}

And the the code of insert() is as below:

public void insertAllStaff(Staff staff){
    ContentValues values = new ContentValues();
    values.put("name", staff.getName());
    Uri uri = contentResolver.insert(CONTENT_URI, values);
}

Every time that I go into this activity, it will insert data to database, the data are the same.

Is there a method that I can go into this activity and it doesn't insert the same data to database?

Upvotes: 1

Views: 487

Answers (2)

Yair Zaslavsky
Yair Zaslavsky

Reputation: 4137

SQLite supports the INSERT NOT EXISTS syntax.

INSERT INTO MyTable(id,text) 
SELECT 123, 'Helloworld' 
WHERE NOT EXISTS(SELECT 123 FROM MyTable WHERE id = 123');

Please use this syntax for performance.
Which content provider are you using with your resolver? You might need to change it and use something else which uses the above SQL statement.

Upvotes: 0

MarkSkayff
MarkSkayff

Reputation: 1374

If you don't want repeated values for your table you have to define a UNIQUE index for the field you feel is "unique".

You do that at table CREATE time, or you can create indexes using the ALTER SQL statement.

Upvotes: 1

Related Questions