Reputation: 1297
i have a method to insert data and check when code is exists or not
if exist dont create insert and if not exists will create insert
but when i try to running the data cant insert to a database
here is my insert code
public void processAddA(DialogWrapper wrapper)
{
ContentValues values = new ContentValues(2);
values.put(DatabaseHelper.CODE, wrapper.getCode());
values.put(DatabaseHelper.ALAMAT, wrapper.getAlamat());
values.put(DatabaseHelper.BATAS, wrapper.getBatas());
values.put(DatabaseHelper.LAT, wrapper.getLat());
values.put(DatabaseHelper.LON, wrapper.getLon());
values.put(DatabaseHelper.LUAS, wrapper.getLuas());
values.put(DatabaseHelper.TANGGAL_AWAL, wrapper.getTglA());
values.put(DatabaseHelper.TANGGAL_AKHIR, wrapper.getTglB());
values.put(DatabaseHelper.USER_ID, wrapper.getUser());
values.put(DatabaseHelper.SENT, "0");
open();
//check if value exist or not.
Cursor c = database.rawQuery("SELECT * FROM petak_tetap where code='"
+ wrapper.getCode() + "'", null);
if(c == null)
{
//doesn't exists therefore insert record.
database.insert("petak_tetap", DatabaseHelper.ALAMAT,
values);
}
close();
}
how to fix that?
Upvotes: 2
Views: 1096
Reputation: 18151
Well first of all c is never null you should use
if (!c.moveToFirst())
But it is a lot easier if you declare your code column to be UNIQUE
and then use insertWithOnConflict
with SQLiteDatabase.CONFLICT_IGNORE
as the last param.
Upvotes: 2