What does the SQLiteOpenHelper class do with the context parameter? - android

I am extending the SQLiteOpenHelper class. My constructor is
public MyDatabaseHelper(Context context) {
super(
context, // ???
"MyDatabase.db", // Database name
null, // Cursor factory
1 // database version
);
}
What does the SQLiteOpenHelper constructor do with the context information?
For my application, the constructor will behave the same regardless of the program state (context). Can I pass null in for the context with out any future problems?

If you supply a null value, it will create an in-memory database instead but you'll need to supply null for the database name parameter as well so it's handled properly.
This is documented in the constructor documentation for context
context to use to open or create the database name of the database
file, or null for an in-memory database
Also, if you view the source code of the SQLiteHelper class itself, you will see it uses the mName value to decide whether to use mContext. View the source code online here:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.4_r1.2/android/database/sqlite/SQLiteOpenHelper.java#SQLiteOpenHelper.0mContext

Related

How to create a database class object inside a fragment

I have a fragment that needs to connect to the database to view its contents and in order to do that I need to get a cursor to my database. Now I have a database class as "DB" and a fragment class "FRAG" . To get a cursor I need to call certain methods of "DB" class inside my fragment. Now to call a method of "DB" class I need a object of "DB" class, the problem is that I am unable to initialize a constructor of "DB" class in fragment class. Syntax is as follows-
Original database constructor is
public DB(Context context, String name, CursorFactory factory,int version) {
super(context,"database", factory,1);
}
I am initializing its object in fragment as follows-
DB ob=new DB(this,"database",null,1);
It gives me a syntax error as -
The constructor DB(Frag, String, null, int) is undefined
How do I initialize a object in this case. Kindly help.
Activity is a descendant of the Context class, not the Fragment.
You have to call the constructor with:
new DB(this.getActivity(),"database",null,1);
where this refers to your Fragment

Correctly open/close a database with Singleton design pattern

I am creating an application which makes a lot of interactions with a database (both read and write operations).
To avoid open/close operations at each request, I created a class extending SQLiteOpenHelper with a Singleton design pattern. This way, I am sure only one instance of the SQLiteOpenHelper and only one connection to the database is made during all the application lifecycle (and not only activity lifecycle).
I also read some articles about ContentProvider, but I am not sure it's a better way.
So, this is the main logic of my Singleton class (onCreate and onUpgrade removed) :
public final class BaseSQLite extends SQLiteOpenHelper {
private static BaseSQLite mInstance = null;
private SQLiteDatabase db = null;
public static BaseSQLite getInstance(Context context) {
if (mInstance == null) {
mInstance = new BaseSQLite(context.getApplicationContext(),
DBNAME, DBVERSION);
}
return mInstance;
}
private BaseSQLite(final Context context, final String name,
final int version) {
super(context, name, null, version);
db = getWritableDatabase();
}
#Override
public synchronized void close() {
if (mInstance != null)
db.close();
}
public Cursor getAllData() {
String buildSQL = "SELECT * FROM myTable";
return db.rawQuery(buildSQL, null);
}
}
So, to access my database, I made this :
BaseSQLite baseSQLite = BaseSQLite.getInstance(context);
baseSQLite.getAllData();
It works perfectly for now. But my question is about the close() method. I really don't know when to call it. Actually, my database instance is the same for every Activies of my application, so I think it's a bad idea to call close() in an onPause() method, because the instance will be potentially (and it will often happens) recreated in the onStart() method of the next Activity. Also, I can't detect the end of my application, i.e. when no activity is visible on the screen anymore.
Can somebody give me some help about this issue ? I found some answer when the database is linked to ONE activity, but no really hint is given for my case.
You should call close anytime you are done writing to your database. For example when you insert data, you will have an open connection to the database that should be closed when it is done.
Reading is different. When you create a SQLite database on your phone, the data is persistent. The database exists and the handler you create provides a convenient way to access that information. Reading the database usually takes place by getting a readable instance of the database and using a Cursor to extract values. In that case you close the cursor when you're done, not the database itself.
You're right that you should not be closing the database connection during separate activities' lifecycle methods. Instead, as suggested above, close the database connection in your handler's methods that write to the database when you are done performing that transaction.

How to call startManagingCursor in non activity Class or in any static method to retrive data from sqlite (in android)?

DBHelper db =new DBHelper(context);
Cursor result = db.weeklyMedicinesTaken();
//WeeklyMedicinesTaken is a function in DBHelper class which returns cursor containing an integer value.
startManagingCursor(result); //this function is a resistance in what i want to do.
while(result.moveToNext())
{
int count=result.getInt(0);
}
result.close();
Actually I have simple classes (non activity classes) in which i want to retrieve data from sqlite and apply some processing and evaluation of data., but the problem is that the code above is working fine in activity but not working in any non activity class or in any static function of activity so that i can call that function from any class.
Any Suggestion Please??
Use getActivity().startManagingCursor(c) or pass an instance of your context to the class inwhich you want to call startManagingCursor()
Lets say your class is sth like this:
Person{
Context mContext;
String name, surname;
Person (Context context){
mContext = context;
}
While creating your Person object you should pass the context like this:
in your onCreate() or somewhere else inside the activity:
Person p = new Person(getActivity());
However, it's not a good practice to manage your cursor outside the activity.
You can examine this tutorial for simple patterns.

Increment android database version via onclick. (SQLiteOpenHelper)

Is it possible (simple) to get the current database version number, increment it, and pass it to SQLiteOpenHelper's constructor from within an activity rather then hard coding the version number like so?
Activity (called from onclick):
public void updatedb(){
//pseudo-code next 2 comments
//int incVersion = getCurrentDBVersion();<==question here
//incVersion = incVersion + 1;
DatabaseHandler dbincrement = new DatabaseHandler(this, incVersion);
}
SQLiteOpenHelper Extension:
public class DatabaseHandler extends SQLiteOpenHelper{
public DatabaseHandler(Context context, int incVersion) {
super(context, DATABASE_NAME, null, incVersion);
}
}
Yes, use something like this to get the database version:
DatabaseHandler dh = new DatabaseHandler(this);
SQLiteDatabase db = dh.getWriteableDatabase();
int version = db.getVersion();
DatabaseHandler dhInc = new DatabaseHandler(this, version++);
You cannot get the current db version number unless you first open the database. So if your intention was to get the installed database version, increment it, and then call the SQLiteOpenHelper constructor with the new version than I don't believe what Sam proposed will satisfy your request.
Here's why:
1) the first line in a DatabaseHandler constructor must invoke the SQLiteOpenHelper (super) constructor, providing your database version.
2) invoking getWriteableDatabase automatically causes the invocation of the onOpen and/or onUpgrade/onDowngrade methods in your DatabaseHandler. Which onXXXX method is called depends on SQLiteOpenHelper's comparison of the installed database version to the version you provided in your constructor initialization above.
I don't know an easy way to find out the installed database version without providing one first.

SQLite DatabaseHelper class

when we create SQLite database from an android application can use a DatabaseHelper class which extend SQLiteOpenHelper.
My constructor is as follows
public DatabaseHelper(Context context)
{
super(context, dbName, null, DATABASE_VERSION);
}
Then the onCreate() method
public void onCreate(SQLiteDatabase db)
{
String qry = "CREATE TABLE DEPT(dept_id INTEGER PRIMARY KEY, deptName TEXT)";
db.execSQL(qry);
InsertDepts(db);
}
But when i create an instance of the DatabaseHelper class, my database havent created yet.
I believe when I create an Object from this class, the constructor executes and since no database created yet it will create database and execute onCreate() method. So definitely an database must be created.
Or untill we execute the following code doesn't it execute the onCreate() method, even if we create an object from the class.
databaseHelper.getWritableDatabase()
Can anyone please explain the execution order of the databasehelper class.
You create an instance of your DatabaseHelper-class, which causes the constructor to be executed. The constructor will execute the mother-classes constructor (SQLiteOpenHelper), which will then check if the Database-file already exists.
If it exists, nothing is done and your object is created.
If it doesn't exist, the Database-file is created and the onCreate-method is called.
You say, your Database doesn't exist. Are you getting any errors in the LogCat? Also, have you tried accessing the Database using the adb?
Order should be like this (as reads SQLiteOpenHelper javadoc)
Constructor
During 1st call of openReadableDatabase() or openWritableDatabase() will be called onCreate
Then will called onOpen
Added
Just checked sources of SQLiteOpenHelper constructor and it reads:
public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {
if (version < 1) throw new IllegalArgumentException("Version must be >= 1, was " + version);
mContext = context;
mName = name;
mFactory = factory;
mNewVersion = version;
}
In contrary openReadableDatabase/OpenWritableDatabase sources consists calls to openOrCreateDatabase() - so constructor doesn't call onCreate
please refer to this
http://androidforbeginners.blogspot.com/2010/01/creating-multiple-sqlite-database.html

Categories

Resources