Deleting in database? - android

I have a question about the databases in Android. I had created in my app a database. If I delete a record from database, for example the last one, and after that I insert a new record in database, the new record is not saved in database in the row where I deleted the other record. That row is empty. It is saved in the next row. Why? Should I do something?

I'm assuming you are talking about an sqlite DB?
If your rowid is a field declared using AUTOINCREMENT, then (from the docs) the "ROWID chosen for the new row is at least one larger than the largest ROWID that has ever before existed in that same table".
You can read about the autoincrement algorithm here: http://www.sqlite.org/autoinc.html
Note that you do NOT have to use AUTOINCREMENT to have your primary key auto select a rowid.

Related

How to rearrange AUTO_INCREMENT Column in SQLite (Android)

I am making an Android App in which there is a List of Users.
And for that I am having a Users table where i am maintaining users' id using AUTO_INCREMENT
db.execSQL("create table Users (u_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, u_name TEXT , u_username text)");
Now my problem is that when i am trying to delete a user from database through ListView.
But after deleting the sequence order is like this : 1,2,4,5,7
So how can i rearrange the AUTO_INCREMENT column to : 1,2,3,4,5 like this.
How to query this thing in SQLite database.
Please help Me, i am stuck.
AUTO_INCREMENT will always increment by one from the last inserted record, no matter if that record still exists or not. if a sequential ordering without gaps is what you want, auto incremental ID is not the proper way to achieve that. Add another int field where you manually keep track of this ordering.

How exactly SQLite database update primary key id?

Suppose I have a table contacts
id Name Contact_No
-----------------------------------------
1 abc 12345
2 lmn 56784
3 pqr 83654
4 uvw 17637
5 xyz 98345
If I delete row 3 from database, what would be the id of rows following the deleted row?
And if I update row 4, will it be given a new id or the id of row 4 will remain same after updating database?
What is the difference between autoincrement and autoincrement not null? Official documentation says that it will degrade the performance and database will work slow. Is it mandatory to write it along with integer primary key?
I have read many stackoverflow answers and also read SQLite Official Documentation but I couldn't get it.
Assuming id is the name of your INTEGER PRIMARY KEY column.
If you update a row, it will never change its id, since it is still the same row. (that's the whole point of update).
Regarding the creation of new ids, everything is in the doc your linked:
Relevant sections :
Without AUTOINCREMENT
On an INSERT, if the ROWID or INTEGER PRIMARY KEY column is not explicitly given a value, then it will be filled automatically with an unused integer, usually the one more than the largest ROWID currently in use.
There is no strict rule, it can be implementation dependent. Usually it will be equal to select max(id)+1. In you case 6, but if you delete row 5, the id 5 can be reused. (But don't rely on this).
With AUTOINCREMENT
If a column has the type INTEGER PRIMARY KEY AUTOINCREMENT (...) the ROWID chosen for the new row is at least one larger than the largest ROWID that has ever before existed in that same table. If the table has never before contained any data, then a ROWID of 1 is used.
Adding NOT NULL to AUTOINCREMENT is therefore pointless.
In your case, the next id is 6, no matter how many rows you delete before that.
If you just use integer primary key then any insert will use the current maximum ROWID (for which id is effectively an alias) plus one. Thus deleting row 3 and inserting a new row will use 6. However, if you were to delete row 5 (leaving the maximum ROWID at 4) a newly-inserted row would get an id of 5.
If you care about id's not being reused, then you need autoincrement. The reason this is slower (and advised against unless you need it) is that the largest ever value is kept in an internal table. Inserts then have to read/update this internal table as part of their operation. If autoincrement was used, then an insert after deleting either 3 or 5 would create a row with id 6.
A normal update of row 4 would leave the id the same, unless you used insert or replace which effectively deletes the row and inserts a new one. Such an insert would follow the same rules as above.

Is the field CONTACT_ID in the contactcontracts table a AUTO_INCREMENT

I am creating a new database for contacts and keeping the contact_id of the conatctscontract field as the primary key. My question is if anyone deletes a row in the contact then will the contact_id for that contact be reused by the android system. If so then how do I prevent that contact id from being used in my application or is there a better approach to this problem?
I'm assuming your using MySQL. The database system auto_increments the contact_id primary key. When the row is deleted that id has already been "used" and is stored in the database as "used" so-to-speak, even though the row itself has been deleted. It will continue to stay that way as long as you don't reset the auto_increment starting point (which the syntax looks something like this)
ALTER TABLE contact AUTO_INCREMENT = 0;
The deleted contact_id's will not be reused if you use the auto_increment feature so long as you don't reset the auto_increment setting for that table (as far as my knowledge goes). It will only continue from the highest ID stored in the database.
Edit: If I'm not mistaken, the column using auto_increment is used in a special database statistics table (unavailable to you, but stored automatically from the database) which stores the latest "auto_incremented" number. Using the syntax above will reset the auto_increment back to 0 and it will resume from there, filling in the gaps that have been deleted.
If you are referring to the inbuilt contactsprovider database then both Contacts table and the Data table have id as AUTOINCREMENT.
So I dont think id will be reused.
You can check the codebase here

Android SQLite Database After delete table, will the id starts from 1?

I have a doubt that if i delete the table using following statements,
SQLiteDatabase db = this.getWritableDatabase();
db.delete(date_difference, null, null);
then if i'm inserting a row as a fresh and first record into the table, will the id primary key auto increment of the records starts from 1 ?
If no ROWID is specified on the insert, or if the specified ROWID has
a value of NULL, then an appropriate ROWID is created automatically.
The usual algorithm is to give the newly created row a ROWID that is
one larger than the largest ROWID in the table prior to the insert.
If the table is initially empty, then a ROWID of 1 is used. If the largest ROWID is equal to the largest possible integer
(9223372036854775807) then the database engine starts picking positive
candidate ROWIDs at random until it finds one that is not previously
used.
So yes, after you delete the table, IDs will start from 1
http://www.sqlite.org/autoinc.html
The documentation provided states that that delete method is a:
Convenience method for deleting rows in the database.
The syntax is:
int delete(String table, String whereClause, String[] whereArgs)
Therefore it won't start from 1 again. It'll continue on from the last increment. If you deleted the whole table, then re-created it, the increment would begin at 1.
SQLite keeps track of the largest ROWID that a table has ever held using an internal table named "sqlite_sequence". The sqlite_sequence table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created**.
The content of the sqlite_sequence table can be modified using ordinary UPDATE, INSERT, and DELETE statements**. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.
So when you delete your table and you re-create it, you should make the SQLITE_SEQUENCE restart from 0.
You should do something like this :
Delete from date_difference;
Delete from sqlite_sequence where name='date_difference';
Care because the field 'table name' in where clause is case sensitive.
Read this for more informations.
Define the primary key field as
INTEGER PRIMARY KEY AUTOINCREMENT DEFAULT 1
Then remove the code if you are doing insertion of any value for the primary key field like following
values.put(KEY_PRIMARY, object.getIntegerValue());

data duplication in sqlite with android app

i am getting information from user in sqlite database.
But when i insert same record which is already in database it is added again.
how i can stop duplication of record in sqlite. I am developing this in android.
I am using mobile number as primary key. still it add that record in database.
Please suggest me appropriate solutions.
Thanks in advanced.
Be aware of the limitations of REPLACE or INSERT OR REPLACE as these will overwrite any custom data your app user has added to these rows in the database - it is not as advanced as UPSERT in other SQL databases.
As mentioned in a previous post you really need to identify what the primary key could be and use this information to either update old data or to remove an old row before inserting the fresh one.
If this is not possible then you could always DELETE FROM my_table or DROP my_table before running the insertions so that there will be no duplicates. This will (for better or worse) also make sure that data that is missing from new imports is not left lying around in your app.
make sure you have set your phone number as Primary Key at the time you created the table.
for example:
String query = "CREATE TABLE IF NOT EXISTS PhoneBook ("+
"TelNum VARCHAR(100) PRIMARY KEY NOT NULL,"+
"Address TEXT);";
db.execSQL(query);
and in case you want to enforce foreign keys defined in your table then call the following method before doing anything in your database
db.execSQL("PRAGMA foreign_keys = ON;"); //enforcing FK
Use REPLACE INTO keyword:
REPLACE INTO my_table (pk_id, col1) VALUES (5, '123');
This automatically identifies the primary key and finds a matching row to update, inserting a new one if none is found.

Categories

Resources