Save SQLite database - android

In my application, I'm using a database to store some data, but if I close my app, my database will be deleted too. So I want to know if there is any mean to save my database and re-use it for the next launch of my app.
I use for the moment
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
in order to create my database.
Thanks for your help

If you are creating database using SQLiteOpenHelper it won't be deleted unless you do it purposely. They are used for persistent memory storage, therefore Android framework doesn't delete it itself unless user clears app data and cache from Application Settings.

To create a database in your Android application you usually subclass SQLiteOpenHelper. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.
In this class you need to override the onCreate() method.
Refer: http://www.vogella.de/articles/AndroidSQLite/article.html#sqliteoverview

use sqliteopenhelper
check this link http://thenewboston.org/list.php?cat=6
It contains tutorials with code included which you can easily understand for the purpose you want to accomplish

Related

What is the best place for SQLite default entires?

I am creating (in android studio) an app which has a couple basic tables. One will be a bunch of exercises (pull ups, push ups ect) and I would like to put a ton of common ones into the table by default.
Where in my code would be the logical place to do that? I have made a databaseHelper class which extends SQLiteOpenHelper. Just not sure if I should..
insert them all in onCreate()
make a databaseHelper method which inserts them all and call it elsewhere
other?
Create a database with your desired data, package it as an asset, and use SQLiteAssetHelper to automatically unpack it into the proper spot for you when you first try to work with the database. This will be faster than running your own transaction(s) to insert the data.

Android and SQL Database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Currently making an app for the very first time, its a massive learning curve for me and the results are satisfying.
So at the moment I have my design all set up, now I need to work on the database side of things.
I have found all the basics to creating tables and adding entries, however I'm a little unsure where I should be inserting this code.
My queries are:
=> Does the code for creating the database tables, inserting/editing/deleting data need to have its own class, separate classes or is it all be done in the class of the 'Form' I have created.
=> How do you connect to the DB so I can call the results, does this need its own class also for showing the entries or can this be done on my 'Entries' class.
Working with android studio, if anyone can give me a better understanding would be much appreciated.
=> Does the code for creating the database tables, inserting/editing/deleting data need to have its own class, separate classes or is it all be done in the class of the 'Form' I have created.
=> How do you connect to the DB so I can call the results, does this need its own class also for showing the entries or can this be done on my 'Entries' class.
I'll answer both of those at the same time:
You don't actually need to make all of the code for the database usage on a separate class, it can be done in the same Android extended class you are working on. Though I highly reccomend you to make a separate one to keep things organized and easier to find.
Basically all of your queries will be managed with a Cursor class, that works pretty much like an iterator, no secrets here.
I would suggest that you take a look at MVC Architecture to help you organize your code and make it as clean as an OxiCelan ad.
Its a pretty easy thing to do. You need to create a class that extends SQLiteOpenHelper. In the default constructor you need to pass a few values.
Take this for example:
public DBHandler (Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
Define a final field DATABASE_NAME and DATABASE_VERSION in the class.
Override onCreate and onUpgrade methods and you are good to go.
onUpgrade method:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACCOUNT);
onCreate(db);
}
In the onCreate you need to give the query to create your table. Create the query as a string and just use execSQL on SQLiteDatabase object to execute that query.

Android concerns with restore database

Imagine the following scenario (I allow backup / restore from my app, I'm doing backup / restore white the entire file.db):
The user make backup of the database.
In the future I do an update on my application which has a new version of the database.
what would happen if the user restore the database with the old version?
How can I avoid this kind of problem?
It would be a good idea to use BackupHelper? I did a simulation of the worst scenario of my database and gave 20k, BackupHelper is recommended for less than 1mb, it would be a good idea to use it? I think my app will never exceed 100kb.
You access SQLite databases via a SQLiteOpenHelper, which provides three callbacks: onCreate(), onUpgrade() and onOpen().
The constructor declares a version parameter, and internally it compares the database version (which is stored in the file) with the supplied argument. If the requested version is newer than the file's, your onUpgrade(db, old, new) is called and you get a chance to alter tables, fill rows and so on.
The restore procedure should simply close all open cursors and helpers and copy the new file in.
May be this is not the best approach but you can do it as:
1- Store the DB Version in the database.
2- After restoring the database, check the DB Version and do the required changes accordingly. Like
void afterRestoration()
{
long dbVersion = get from db;
if(dbVersion == 1)
{
alter table1 add column1;
}
else
{
}
}

Access DB outside an activity on android

I am trying to access my DB outside an activity and I get an error.
My architecture is having a wrapper for the DB, so when I want to display something in the activity I just create a class and take the information from it.
for example I want to create a HUMAN class that will access the DB through the db adapter class that I created. in the adapter class I return a cursor to the relevant row/s.
I tried doing so using startManagingCursor and I get an error saying it is undefined, when I try using this method in activity everything seems fine.
basically please try and give me an example of how to handle my DB in the right way.
I have a very big DB and I thought that creating a class for each table on the DB and than let the table get it's information is the right way, but I am not sure how to do that.
what I thought is lets create an instance of human with the id of 3 than in the constructor of Human (which is not an activity) go to the db get the information in a cursor and save all the information in the data members.
Thank you

SQLite database on SD card

I'm looking to create a sqlite database on the sd card (don't want to use up the user's internal storage). I'm familiar with the OpenHelper pattern:
public DatabaseFoo(Context context) {
OpenHelper openHelper = new OpenHelper(context);
mDb = openHelper.getWritableDatabase();
}
private static class OpenHelper extends SQLiteOpenHelper {
public OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
...
so if we want to create on the sd card, I think instead we have to use:
public static SQLiteDatabase openOrCreateDatabase (String path,
SQLiteDatabase.CursorFactory factory);
But what is the "factory" argument supposed to be, what factory should be used?
Also a bit worried about what happens if the user removes the SD card while my app is in use..
Thanks
I haven't tried to do what you describe there, but presumably it could be done and might work -- with a few caveats. First, the external storage (SD card) is not secure, so any other application, or the user, could read/write to it. Second, as you noted, when it's unmounted the DB goes away.
Because of these disadvantages, you would probably be better off to try to use an internal storage database (the default), that is small and possibly includes pointers to external data (like images or files) -- that themselves can be on the external storage (and that have placeholders, or other handling, when the external storage is not available).
Still, if you want to try it, you might be better off override the getDatabasePath method of Context, such as with your own Application object, and then pass that into a regular SQLiteOpenHelper. Then you wouldn't have to worry about the cursor factory (which is optional, as the source confirms -- so just pass null if instead you want to go that route).
Do this in your SQLiteOpenHelper constructor:
DatabaseHelper(Context context) {
super(context, context.getExternalFilesDir(null).getAbsolutePath() + "/" + DATABASE_NAME, null, DATABASE_VERSION);
}
It will create the database in the app's folder on the sdcard: /sdcard/Android/data/[your_package_name]/files.
In that way the database will be seen as part of the app by android and removed automatically if the user uninstalls the app.
I my app I have a large database and it will in most cases not fit on old phones internal memory, e.g. HTC Desire. It runs great on the sdcard, and most apps are "moved to sdcard" themselves anyway so don't worry about the database not being accessible, because the app won't be accessible it self.
Cursor factory is used to return an instance of your custom Cursor implementation.
Generally you just use SQLiteCursor, in which case null is passed as factory argument.
Then make your own flat database - most people have very little internal memory, and its annoying that they eat it up with huge database.
And as for the 'what if they remove the SD' scenario - if the user removes the card obviously its not going to work! Clearly. Just check you didn't get an error when trying to interact with the base, and if you did, just tell you user - problem solved.
public DataBaseHelper(final Context context) {
super(context, Environment.getExternalStorageDirectory()
+ File.separator+ MYDATABASE_NAME, null, MYDATABASE_VERSION);
}
Also Add permission in android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I would recommend against putting a database onto an SD card - you will significantly decrease the lifespan of the card, since it has a (large, but still existent) limit on the number of writes possible and databases require quite a few writes.

Categories

Resources