The sqlite database insert duplicated data - android

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?

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.

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.

Related

What is the difference between inserting data using ContentValues and Raw SQL in SQLite Android?

I want to know the difference between inserting data using ContentValues and inserting data using Raw SQL in SQLlite(Android), Is there a advantage using content values?
To perform insert, read, delete, update operation there are two different ways:
Write parameterized queries (Recommended)
Write raw queries
Parameterized Queries: These are those queries which are performed using inbuilt functions to insert, read, delete or update data. These operation related functions are provided in SQLiteDatabase class.
Raw Queries: These are simple sql queries similar to other databases like MySql, Sql Server etc, In this case user will have to write query as text and passed the query string in rawQuery(String sql,String [] selectionArgs) or execSQL(String sql,Object [] bindArgs) method to perform operations.
Important Note: Android documentation don’t recommend to use raw queries to perform insert, read, update, delete operations, always use SQLiteDatabase class’s insert, query, update, delete functions.
Following is an example of raw query to insert data:
public void insertItem(Item item) {
String query = "INSERT INTO " + ItemTable.NAME + " VALUES (0,?,?)";
SQLiteDatabase db = getWritableDatabase();
db.execSQL(query, new String[]{item.name, item.description});
db.close();
}
While using raw queries we never come to know the result of operation, however with parameterized queries function a value is returned for success or failure of operation.
Insert: To perform insert operation using parameterized query we have to call insert function available in SQLiteDatabase class. insert() function has three parameters like public long insert(String tableName,String nullColumnHack,ContentValues values) where tableName is name of table in which data to be inserted.
Here is simple example:
//Item is a class representing any item with id, name and description.
public void addItem(Item item) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name",item.name);
// name - column
contentValues.put("description",item.description);
// description is column in items table, item.description has value for description
db.insert("Items", null, contentValues);//Items is table name
db.close();
}
For more Information see this Link

How to update part of the database - Android SQLite

I'm new in android. I'm using SQLite database to store data. I have 2 column in this database which are containing unique data for each user.
The problem is when user will get an update, then the update will override the personal data. I want to update the database except 2 columns.
Here is my Initialize Database:
INSERT INTO WORDS (_id, unlocked,solved,score,word,letters,image,suggestion) VALUES (1,1,0,0,'example','example','pics/example.png','example');
As you can see, the 'solved' and 'score' has 0 values. I don't want to update these values. So I don't want to drop the entire database before the update, I would like to keep those 2 values, and make sure the update is not override those data.
Use like this
UPDATE table_name SET column_name1='value', column_name2 = 'value1' WHERE condition_column='value'
You can check it with weather DB table contains that user id or not, if not then do insert query as you are doing
If record found, just do updateQuery:
UPDATE WORDS set unlocked = 1, word = 'example',letters = 'example',image ='pics/example.png',suggestion='example' WHERE _id=1;
I have to say, you need to research, because this tag it's very trivial. So I recommend you to read more about.
this could be:
DatosSQLiteHelper usdbh = new DatosSQLiteHelper(this, "myDatabase", null, 1);
SQLiteDatabase db = usdbh.getWritableDatabase();
if(db != null)
{
//add all atributes for update
ContentValues registre = new ContentValues();
registro.put("myvar1", "value1");
registro.put("myvar2", "value2");
registro.put("myvar3", "value3");
int numcol = db.update("mytable", register, "_id_="+1, null);
if (numcol == 1)
{
Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
}
}

Saving to sqlite using insert or update

i am using the below code to insert row to my db. every thing is fine but this method does not save row to the db. what is wrong with this code :
public void insert(Restaurant rest) {
String[] args = { String.valueOf(rest.getId()), rest.getName(),
rest.getDescription(), rest.getAddress(), rest.getTel1(),
rest.getTel2(), rest.getTel3(), rest.getEmail(),
String.valueOf(rest.getCategory()),
String.valueOf(rest.getRegion()) };
m_db.rawQuery(
"INSERT OR REPLACE INTO restaurant(id,name,description,address,tel1,tel2,tel3,email,category,region) VALUES(?,?,?,?,?,?,?,?,?,?)",
args);
}
Use execSQL() and not rawQuery() for raw SQL that modifies the database.
rawQuery() alone won't execute the SQL; you'd need to call one of the moveTo...() methods on the returned Cursor to execute it.

Insert or Replace Multiple Row with where condition in SQLite Query

I need a single SQLite query to insert or update in SQLite table.
MyTable:
Id(Primary key and not null)
Name
PhoneNumber
Expected Query: If the Id is not present then have to insert a new row
and If the existing row value is changed then update the row when inserting multiple row.
EDIT 1:
I have posted INSERT query i have tried in Insert Multiple Rows in SQLite Error (error code = 1). Like that i I have tried using "INSERT OR REPLACE". But it is working with Firfox SQLite Manager Not working with Android SQLite.
I have used sDataBase.execSQL(query) to execute this query.
Try this:
String sql = "INSERT OR REPLACE INTO MyTable (Name, PhoneNumber) VALUES (?,?)";
SQLiteStatement st = db.compileStatement(sql);
And write or update:
public void writeOrUpdateData(ArrayList<MyClass> data) {
try {
db.beginTransaction();
for(int i = 0; i < data.size(); i++) {
st.clearBindings();
st.bindLong(1, data.get(i).getName());
st.bindString(2, data.get(i).getPhoneNumber);
st.executeInsert();
}
db.setTransactionSuccessful();
}
catch(Exception e) {}
finally {
db.endTransaction();
}
}
This way you get bulk insert/update, which is quite efficient!
I have created database with primary key only in Firefox SQLite Manager. I have missed this in SQLite database in Android. Now i have created database with PRIMARY KEY and NOT NULL. Now Working fine.

how to delete rows in a table on database using android sqlite3

i'm unable to delete row in a table using sqlite 3.In my code i would like to compare two
values an then delete the data in a table but it is not possible please help me.
while(authCur.moveToNext())
{
db.delete("auth_tab",authCur.getString(0)+"=?" , new String[] { user });
db.delete("auth_tab", null, null);
}
Deleting data
Once data is no longer needed it can be removed from the database with the delete() method. The delete() method expects 3 parameters, the database name, a WHERE clause, and an argument array for the WHERE clause. To delete all records from a table pass null for the WHERE clause and WHERE clause argument array.
db.delete("auth_tab", "authCur.getString(0)=?", new String[] {user);
Simply call the delete() method to remove records from the SQLite database. The delete method expects, the table name, and optionally a where clause and where clause argument replacement arrays as parameters. The where clause and argument replacement array work just as with update where ? is replaced by the values in the array.
or
public void deleteContact(long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(auth_tab, KEY_USER + " = ?",
new String[] { user) });
db.close();
}
WATCH more, and you tube video, how to delete.

Categories

Resources