Should there be one SQLiteOpenHelper for each table in the database? - android

Is it better to have a single big SQLiteOpenHelper subclass that defines onCreate and onUpgrade methods for every table in the database, or is better to have many SQLiteOpenHelper subclasses, one for each table?
Is there a best practice? Or are both acceptable, but with different good and bad side effects?

You should have a single SQLiteOpenHelper class for all the tables. Check this link.

Just for the sake of a different approach:
You can always overried on the onOpen(..) method have it called your onCreate(..) . Be sure to use the "CREATE TABLE IF NOT EXISTS..." statement rather than "CREATE TABLE"
#Override
public void onOpen(SQLiteDatabase db) {
onCreate(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FRIENDS_TABLE = "CREATE TABLE IF NOT EXISTS ...";
db.execSQL(CREATE_FRIENDS_TABLE);
}
You do that with every class that extends from SQLiteOpenHelper

#TheReader is right. I prefer a single SQLiteOpenHelper for all tables, here is what i do: pass a List of "table creation" sqls to the Constructor of the SQLiteOpenHelper subClass, then in the onCreate function iterate the list to create each table.
so my SQLiteOpenHelper subclass looks sth like this:
public ModelReaderDbHelper(Context context, List<String> createSQLs, List<String> deleteSQLs){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.TABLE_CREATION_SQLS = createSQLs;
this.TABLE_DELETE_SQLS = deleteSQLs;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
for(String oneCreation : TABLE_CREATION_SQLS){
sqLiteDatabase.execSQL(oneCreation);
}
}
But that comes another problem: after adding a new table, and install the new version of the app with an existing old one installed, the new table won't be created, because the existence of the old database will prevent the onCreate function from being called. So user has to uninstall the app first, and install the app completely. The DATABASE_VERSION helps, it seem android will not execute the onCreate function if and only if the a existin database with the same name and the same DATABASE_VERSION

Related

Create new table in existing DB in separate SQLiteOpenHelper class

In my already created and deployed application, I've created a database MainDB, using a single class file which extended SQLiteOpenHelper, viz.
public class BaseSQLiteOpenHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "MainDB";
....
....
}
Issue is I've tied this class, too much to a particular functionality.
Now I'm adding a totally new module in application, which will also interact with DB, but with different new tables.
Issue is I can't use the same class, as it is conflicting in more than one way. And even if I redesign the code, it will only add complexity from functional/understanding point of view.
So, I've decided to use same DB, but different tables.
Now I've already created DB in BaseSQLiteOpenHelper class.
So, how can I create new tables in seprate class using same DB?
One approach is to use separate Database as well, Or,
Create my new table in onCreate() in BaseSQLiteOpenHelper class only (issue with this is mentioning new table in same class seems awkward, as this class has nothing to do with my new table).
Please suggest.
Thank You
First check the current database version for this database
private final static String DATABASE_NAME = "MainDB";
private static final int DATABASE_VERSION = 1;
public BaseSQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
and increment the database version(DATABASE_VERSION), and add your new table query in on Upgrade and oncreate method like below.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("old query no need to change");
db.execSQL("Create your new table here");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
db.execSQL("Create your new table here as well this for update the old DB");
}
}
Done!!!

can i remove all data set by the previous install of app Android

Is it possible to delete any existing data set by a previous install of same app (databse tables and shared preferences etc) when the app is re-installed?
I have an app that stores some values in sqlite database, if the app is re-installed without prior properly uninstalling. I face problems from previous database entries etc.
If uninstalling the app didn't do the stuff try this :
System Parameters -> Manage Applications -> Your Application -> Clear data
If you click on the button (Clear data) you will see a dialog which shows you what kind of data will be cleared.
Edit:
If you want to do that programmatically, you can :
Change database version in the super method of the constructor:
super(context, DATABASE_NAME, null, NEW_DB_VERSION);
Add a drop statement before creating tables.
database.execSQL("DROP TABLE IF EXISTS your_table");
database.execSQL(" CREATE TABLE your_table ...");
Proceed to a hard drop of the database:
this.context.deleteDatabase(YOUR_DATABASE_NAME;
Its very Simple.
First Delete the table using drop query
sdb.execSQL("DROP TABLE IF EXISTS tablename");
and then again use the create table query
sdb.execSQL(" CREATE TABLE tablename(col1 TEXT PRIMARY KEY)");
or
delete the DB file using file explorer in path data->data->package->databases->dbname
update the Database version to greater value in the OpenHelper, it will automatically drop all the tables in database and recreate them.
For shared preferences.. you can clear them from the OpenHelper when onUpgrade is called.
Like Ankit Popli said, Using version is the right way to go:
public class Database extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "YourDBName.db";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// ALl the deletion operation here.
db.execSQL("DROP TABLE IF EXISTS "+Database.TABLE);
onCreate(db);
}
}
AndroidSqlite will automatically call onUpgrade function when the version number is incremented. Do all the database deletion there.

Android Database

I am designing an application for an online exam. And I created a database using SQLite Browser and pulled it to Eclipse. In an emulator its working fine; it is able to retrieve and store data. But the problem comes when I place the .apk file on the mobile. On the mobile it's unable to retrieve the existing database. I am unable to bind the database file along with the .apk file, even after placing it in the assets folder.
Can anyone help?
Details:
Registration module
User Test module (display the questions from database)
Score submission module
How are you querying on database ?
The correct way is not to place a separate db in your code, but to create one dynamically. For e.g. the following code :
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSql("/*Put Create Table sqls here*/");
//onCreate will be called only once( when db doesn't exists for application, it creates here with the code)
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Use a database helper class like this in your code.
Now whenever you want to query on your db you can do it like this :
dbHelper = new DatabaseHelper(ctx);
db = dbHelper.getWritableDatabase();
//Start querying on db.(if it is not created oncreate() of dbhelper will create it for you.
So simply put your initial db create,/insert statements in oncreate() of dbhelper

Android app create table

I'm using SQLite to create a database table for my app. I've searched online but haven't found the answer yet: Do I need to create a database first or is there a default database for each app?
I've written the following DBHelper class. It's in a separate file. How Do I call it when the app starts?
public class DataBaseHelper extends SQLiteOpenHelper{
final String CREAT_TABLE = "CREATE TABLE IF NOT EXIST `employee` ("+
"`id` int(11) NOT NULL AUTO_INCREMENT,"+
"`firstName` varchar(30) NOT NULL,"+
"`lastName` varchar(30) NOT NULL,"+
"PRIMARY KEY (`id`)"+
") ;";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREAT_TABLE);
}
}
You don't have to create the database yourself.
You specify the database name (the sqlite file name) when you call the superconstructor of your open helper.
This will create or update the database with that name when needed (depending on which version number you send in vs. the current version number meta data).
I don't know what your constructor looks like but let's say it looks like
public DatabaseHelper(final Context context) {
super(context, "mydatabase", null, 0);
}
Then the SQLiteOpenHelper will create a database named "mydatabase" when you call getReadableDatabase() or getWritableDatabase(). It's all in the docs.
You declare your database name in the constructor
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

Creating initial SQLiteDatabase when app is installed

I am writing an app that displays fun-facts (and the source they are from). The user can browse through the facts one by one.
Here is the design I thought of :
Create a table in SQLiteDatabase with a text column that stores the fun-fact and a second column that stores it's source. (not sure if this is the best way to go about doing it, but I want the app available even without the network)
My question is, when database is initially created on the device, should I manually populate the database from within the code, something like this pseodo-code:-
#Override
public void onCreate(SQLiteDatabase db) {
//Create the table
//Populate the table
//Insert statement 1
//Insert statement 2
//Insert statement 3
...
//Insert statement 500
}
Surely there must be a better method to create the initial database when the app is installed?
Are you certain that you really need a databse? Doesn't it just add unnecessary overhead to something so trivial?
Can't you just declare the array in your code, or am I missing something? Whether it's in the db or your code, it is taking up space. The db will add some overhead to that and vious?will take some time to load, plus your code has to handle errors, etc.
Woudl you not be better off with a simple array declared in your code? Or am I misisng something obvious? (maybe users can d/l a new db? But is that so much more overhead than d/ling a new program?)
If I'm way off, please explain (rather than downvoting). I am trying to help
Edit: presumably you already have your facts soemwhere? Maybe in a text file? You could just write code to parse that and initialze and array (or populate a db). It should bascially be a short for loop.
use a class derived from SQLiteOpenHelper
i already wrote sth obout this on my blog www.xenonite.net
public class myDatabase extends SQLiteOpenHelper
{
private static final String DB_NAME = "database.db";
private static final int DB_VERSION = 1;
public MyDatabase(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE tbl_test ( id INTEGER PRIMARY KEY AUTOINCREMENT, test TEXT NOT NULL )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS tbl_test");
onCreate(db);
}
}
you can use this like
myDatabase db = new myDatabase(getApplicationContext());
sql = "INSERT INTO tbl_test (test) VALUES ('xyz')";
db.getWritableDatabase().execSQL(sql);
String sql = "SELECT id FROM tbl_test";
Cursor result = db.getWritableDatabase().rawQuery(sql, null);
int value;
while(result.moveToNext())
{
value = result.getInt(0);
}
on every call to db, myDatabase.onCreate() is called, so your database will be created on the first run. when changing the table structure, implement onUpgrade() and increment DB_VERSION

Categories

Resources