Android SQLite adding rows only once - android

From what I understand, once a SQL db is created and populated it remains on the device until the app is uninstalled. For performance reasons I don't want to re insert all my rows every time the app is lauched, how can I wrap my insert statements so that I populated the db only the first time the app is launched?
Right now I have the inserts in the onCreate() method of my main activity. What is the best practice?
Thanks

Use SQLiteOpenHelper to manage your databases. Put your database creation and population code in the onCreate() of the helper - it gets invoked exactly once when the database file did not exist.

before you could insert check for no of rows in the table.
if(rows<1)
{
insertValues
}
else{
//Do nothing //
}
you can get no of rows by using
int numRows = (int) DatabaseUtils.queryNumEntries(db,table_name);

Related

Insert, Update and Delete from a SQLite Database (Android)

I already have a SQLite Database setup which I am using as cache for the Android application. The application does a HTTP Request and gets back a List of objects which I can insert into the db. After the first request, if I do anymore requests, how do all of the following in a better way:
1) insert all new objects from the list
2) update all objects that were already in the db
3) delete all rows that were not there in the latest list of objects.
I know that options 1 and 2 can be done using the "INSERT OR UPDATE" query. How can I manage the 3rd option efficiently?
Right now my approach is to delete all from table and then insert all. But that isn't very efficient. Any ideas how to improve it?
For that you can use the ids of the rows. For doing that first retrieve all the rows which you want to delete using SELECT query and add it a temporary arraylist, then use for loop over the arraylist to delete all those rows by using DELETE query.
You should do your operations using the applyBatch() method of the ContentProvider (http://developer.android.com/reference/android/content/ContentProvider.html#applyBatch(java.util.ArrayList)).
You can perform this method in a separate thread asynchronously so that you do not block anything else. You will have to create a list of ContentProviderOperations. In fact, you only need to specify the ones you need to insert or update within the ArrayList and implement the applyBatch() method such that it will automatically delete the rest of the entries in the database.
To answer your question about how to delete the entries not in the table, the logical assumption would be to search through your data sequentially and then delete the ones that do not need to exist.
I guess the intention is to refresh the Http request result set saved in the database. So I think the most efficient way is do a transaction or batch operation to delete all rows from the table first and then insert the new rows. A transaction might be better so that the result rows are either all new or all old, but not mixed.

destroy the database- android life cycle

Hello I am trying to figure out a way to destroy my database every time the application starts either by returning from the background or reopen after it was closed. The issue is that when I am trying to run my application for the first time I get a null and my application crushes.
My application:
The user is prompt with a login screen and I create the db, move to another activity to perform a query. From this activity the user cannot go back to login, and will be only able to go to the phone home screen. When I will go to the home screen and re open the application I want to wipe out the db and start like it is my first time the user uses the application.
I know that this is not actually practical for an application, but this is just for learning.
I tried to do db.close() and context.deleteDatabase(db.getPath()); in onResume and onRestart, but this always crushes my application. I also tried to check that 'db.getPath()!=null' , but this did not help either.
thank you
Since you are aware that is not the most practical way to use databases I guess I won't bug you for that.
What you want to do is not to call the method to delete the database content during on Resume() or on Restart(), you actually want to call that via on Stop().
The method you want to use is
db.delete(String table, string whereClause, String [] whereArgs);
Passing the name of the table you want to delete, i.e "user_food_database", a whereclause which would be null in your case since you want to delete ALL rows, and null for whereArgs.
Here's the official doc:
"Convenience method for deleting rows in the database.
Parameters
table the table to delete from
whereClause the optional WHERE clause to apply when deleting. Passing null will delete all rows.
Returns
the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause. "
You can also call:
deleteDatabase(File pathToDatabase)
in case you have more than one table in your database, but recreating the database itself everytime is expensive, and deleting only the content may result better.
I suggest that you simply wipe the database, i.e., delete all data (or even drop the tables). This is not a direct answer to your question, but has the same effect.
Just drop all tables in the open() method of your SQLiteDatabaseHelper and recreate the tables by calling onCreate(db). Works of course only when you are opening the db only once per app start.

SQLite usage with Android

For my app, I need to have a database containing one table with 4 columns in it. This tables and its parameters will be static after creation, so that they will stay in the same place with the same data to be listed in a list view.
I have the DatabaseHandler for this purpose, but what I'm asking is how do I define this database in code? Does it build again every launch or is it only with the first launch? How does it work?
There are many ways of doing it. The one i follow is I will create database and tables in launch activity. Then i will insert data by counting the number of records in the table(Only for static table).So if(number of records == 0) then insert data into database. Otherwise do code for your app. It should work.
EDIT
This is the code to get total number of records in the database
In Database Class
YourDatabase
public class YourDatabase extends SQLiteOpenHelper{
//coding for table create and insert records goes here
//Your tables total number of records can be identified by following code
public long yourTableCount()
{
SQLiteDatabase db = getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, YOURTABLE_NAME);
}
}
Your Activity
Calling Database class from your activity
YourDatabase db = new YourDatabase(this);
long numberofrecords = db.yourTableCount();
if(numberofrecords == 0)
{
//Insert your data in to database
//This will happen only in first launch because after that the numberofrecords == total number of records inserted in the database.
}
You can create the database manually using a database manager. Once you have the database defined in your assets folder it will remain there and be compressed within the apk file on build. Try SQLiteManager which has a free trial version that will let you design you database. Or use a firefox addon here: https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

How can I recreate a database with default values?

In my application, I want to delete my existing database and create a new one with default values. Default values can be inserted to the database from XML.
Does anyone have any idea on how to reuse a database?
Assuming that you are using a SQLite database, to delete all the rows from all of your tables inside your database you can use db.execSQL() and heed the advice from this question Drop all tables command:
You can do it with the following DANGEROUS commands:
PRAGMA writable_schema = 1;
delete from sqlite_master where type = 'table';
PRAGMA writable_schema = 0;
you then want to recover the deleted space with
VACUUM
and a good test to make sure everything is ok
PRAGMA INTEGRITY_CHECK;
If you haven't written a way to read your XML data yet, this is excellent reading: Store parsed xml data to sqlite ? Android
Well basically that's not an Android specific question.
Firstly when do you want to recreate the database with default values and how to trigget it.
In an UI event like button click etc?
Or when you start/stop or destroy your activity?
In any cases you need to drop the database and recreate the whole structure (tables,relationships etc.) again.

Android SQlite database table, adding column

I'm trying to add a column to my database table which was created a while back and every time i try to run the app with the new column in the database adapter it crashes.
Why is this happening? I have changed the name of the database so it acts like a fresh table but this still doesn't work..
Please help????
If you are using a subclass of SQLiteOpenHelper as a lot of the Android examples suggest, you need to increment the DB_VERSION int that gets passed to the constructor. Otherwise the onUpgrade method doesn't get called and your db schema doesn't change.

Categories

Resources