Sqlite open helper insert else update? - android

I want to insert data successfully
Here is my code:
public void insertData(String strTableName,
ArrayList<HashMap<String, String>> arrListproductdatabase) {
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for (int i = 0; i < arrListproductdatabase.size(); i++) {
// cv.put(columnName, arrListOfRecord.get(i).get("name"));
cv.put(columnproductname,
arrListproductdatabase.get(i).get("product"));
cv.put(columnproductprice,
arrListproductdatabase.get(i).get("price"));
cv.put(columnproductquantity,
arrListproductdatabase.get(i).get("quantity"));
cv.put(columnproductid,
arrListproductdatabase.get(i).get("productID"));
cv.put(columnresturantID,
arrListproductdatabase.get(i).get("resturantID"));
db.insert(strTableName, null, cv);
}
I want that when I have to press add button again, that time it should check if the product is already inserted, and in that condition it should update and all.
I don't want to create any duplicate value.
Any help would be appreciated!

you can check for the distinct values in the db. please follow the link to have more details
android check duplicate values before inserting data into database

Set 'Product' field as unique key. So when duplicate value arrives from standard insert, it will simply return -1 and the error message will be swallowed.
You can control the behavior by using insertWithOnConflict (String table, String nullColumnHack, ContentValues initialValues, int conflictAlgorithm) where you also specify a conflict algorithm that can be of values:
CONFLICT_ABORT
CONFLICT_FAIL
CONFLICT_IGNORE
CONFLICT_REPLACE
CONFLICT_ROLLBACK
Check out the reference for descrption of the conflict resolution types.
There is also an updateWithOnConflict

You can do that like this :
public boolean checkProduct(String product){
// shold open database here
Cursor mCursor =
db.query(true, DATABASE_TABLE, null, "product='" + product+"'", null, null, null, null, null);
if(mCursor != null){
mCursor.close();
// shold close database here
return true;
}
// shold close database first here also
return false;
}
Hope this helped you.

Related

delete all rows from sql in android studio

my app should delete a specific row in the sql database by this method
public void delete(int id){
open();
sqLiteDatabase.delete("item","id = "+id,null);
close();
}
and it should also delete all rows if the user want that by this method
public void deleteAll(){
cursor=sqLiteDatabase.rawQuery("select * from item",null);
cursor.moveToFirst();
i=1;
while (!cursor.isAfterLast()) {
sqLiteDatabase.delete("item","id = "+i,null);
i++;
System.out.println(i);
cursor.moveToNext();
}
}
when the user use deleteAll() alone it is work but when he use it after using delete() it delete all rows before the deleted one using delete()
is the problem in deleteAll() method ? and how to fix it?
Your delete() function only deletes rows with the given id. If you want to delete all rows, then just do
sqLiteDatabase.delete("item", null ,null);
There is no reason to write your own loop especially since you never use the Cursor anyway.
Additionally, you should never use string concatenation for the "where" clause in a SQL statement. Instead use "id = ?" and provide a String[] with the values:
db.delete("image","id= ?", new String[] {id});
Here is an example of how to delete a particular column with an id:
SQLiteDatabase db= this.getWritableDatabase();
db.delete("image","id= ?", new String[] {id});
Toast.makeText(context,"Delete successfully",Toast.LENGTH_LONG).show();
Hope this will work for you

Queries in SQLite

I have the following insert statement in my app which work.
Before the insert I want to first check the database if the value name does not exist in the name column.
If it does not exists I want to continue with the insert, else display an error message.
How do I incorporate it into my existing statement below?
public void insert(HashMap<String, String> queryValues){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
Cursor c = database.query("SELECT * FROM user_details where" + "name=?", new String[] {values.put("name") });
if (c.getCount() > 0) {
// don't do it
return;
}
else {
values.put("name", queryValues.get("name"));
values.put("age", queryValues.get("age"));
database.insert("user", null, values);
}
database.close();
}
The correct way to do this is to add a unique constraint on the name field, and then use insertWithOnConflict() with a last argument of CONFLICT_FAIL. That's actually the default behavior. Your insert will fail if it would otherwise cause a constraint violation (insert() will return -1).
If you don't want to do that, there's no magic. Query your DB for a row with the given name field. If you are returned >0 rows, don't perform the insert.
Cursor c = db.query(..., "name=?", new String[] {theName}, ...);
if (c.getCount > 0) {
// don't do it
return;
}

Avoid duplicate entries in SQLite

I am writing a small application in android to store basic details about person using SQLite.
I insert data using this function
public void insertData(String user,String p_no,SQLiteDatabase db)
{
ContentValues cv = new ContentValues();
cv.put(NAME, user);
cv.put(PHONE, p_no);
db.insert("MYTABLE", null, cv);
}
The above function allows duplicate names to be stored.
So I wrote a function that will first check whether a name exits and then enter.
public void insertData(String user,String p_no,SQLiteDatabase db)
{
Cursor resultSet=db.rawQuery("select NAME from MYTABLE where NAME = '"+user+"'",null);
if(resultSet==null)
{
ContentValues cv = new ContentValues();
cv.put(NAME, user);
cv.put(PHONE, p_no);
db.insert("MYTABLE", null, cv);
}
else Toast.makeText(context,user+" already exists",Toast.LENGTH_SHORT).show();
}
But the problem is now toast comes up every time I insert meaning even if the row is unique it is not inserted.
Why resultSet is not null even when there is no such row?
It is because RawQuery never returns null cursor, and that's what your checking criteria is, so it is failing always, and trying to add new value in DB.
I am not able to find the documentation where I learned it, but I will update as soon as possible.
You can check if you have values in cursor using -
if(cursor.moveToFirst())
because it is possible to have an empty cursor. Change your check like
if(cursor.getCount() == 0)
this way, if the cursor is not null, you check if it contains something too.
Probably this is not the best way to handle duplicates, in my opinion. You should mark your column as unique, and use insertWithConflict, to decide what to do in case you have already an entry with that value
Check
if (resultset.getCount() == 0)
Also, create Name as unique key to avoid duplicates. Instead of checking it everytime.

How to prevent to insert duplicate value in sqlite database (if duplicate then overwrite)

I had created two table in my database, In both table I am inserting value at the same time, now what I want to do is that, I want to insert record in second table, but the condition is that, if there is two same record then I want insert only one record not duplicate value, In second table there is two field one is id and second is category, when user insert two same category that time I want to insert only one entry, below is my code which is not working properly, It insert all record accept duplicate value..
public long InsertCat(String idd, String cat)
{
try
{
SQLiteDatabase db;
long rows = 0;
db = this.getWritableDatabase();
ContentValues Val = new ContentValues();
Val.put("IDD", idd);
Val.put("Category", cat);
Cursor c = db.rawQuery("SELECT * FROM " + TABLE_CATEGER + " WHERE Category='"+cat+"'",null);
while(c.moveToNext())
{
if(c.getString(0).equals(cat))
{
flag=true;
}
}
if(flag==true)
{
rows=db.update(TABLE_CATEGER, Val, "Category='"+cat+"'" , null);
System.out.print(rows);
db.close();
}
if(flag==false)
{
rows = db.insert(TABLE_CATEGER, null, Val);
System.out.print(rows);
db.close();
}
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
Put all your values inside ContentValues and then call this on writableDatabase
db.insertWithOnConflict(tableName, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
EDIT:
Well all you need is only this part of code
SQLiteDatabase db;
long rows = 0;
db = this.getWritableDatabase();
ContentValues Val = new ContentValues();
Val.put("IDD", idd);
Val.put("Category", cat);
rows = db.insertWithOnConflict(tableName, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
insertWithOnConflict methods follows the last parameter as the reaction algorithm when an duplicate row is Found. And for a duplicate row to be found, the primary keys has to clash. If all this satisfys the row would surely get Replaced :-/ If not something else is going wrong..
While creating your table, put constraint on your column(Primary key or Unique key).This will not only the duplicate value to be inserted into your database.
This is working for me,and i also created Category as a primary key..
ContentValues Val = new ContentValues();
Val.put("IDD", idd);
Val.put("Category", cat);
long rows=db.insertWithOnConflict(TABLE_CATEGER, null, Val,SQLiteDatabase.CONFLICT_REPLACE);
System.out.print(rows);
Log.d("kkkkkkkkkk",""+ rows);
db.close();
return rows; // return rows inserted.
Check with the primary key of which you want assign then while inserting check with on duplicate key..
if you want you update the row
on duplicate key update
As mentioned i am writing the code on duplicate key
INSERT OR REPLACE INTO TABLE_CATEGER(value1,value2,value3)
Use the following query
INSERT OR REPLACE INTO table_name (idColoumn, categoryColumn) VALUES (?, ?)
It will add new row if it does not exist or update row if it exists.
hope this will help you.
use insertWithOnConflict() method instead of insert()
response = sqLiteDatabase.insertWithOnConflict(TABLE_TRACKER_LOGS_LINES, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);

check value if exist sqlite error insert

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?
use this condition it will work
if (c!=null && c.getCount()==0)
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.

Categories

Resources