leojg
leojg

Reputation: 1186

How does it work SQLiteOpenHelper Context

I have an app with two activities.

One of them list several values while the other add new values to a DB.

I have a class wich extends from SQLiteOpenHelper and manages the DB connections, queries, etc.

Now, I understand that in the constructor of SQLiteOpenHelper you have to pass a context which is used to determine if it has to create a new DB or open an existing one.

But if I have one instance of the SQLiteOpenHelper class in each activity, then the context would be different.

Is there a way to avoid this?

Thanks.

Upvotes: 8

Views: 5310

Answers (3)

Vijay Vankhede
Vijay Vankhede

Reputation: 3058

Actually, the created database is associated with the context's application package. So it doesn't matter whether you have passed the Application context or Activity context.

Context.java

/**
 * Open a new private SQLiteDatabase associated with this Context's
 * application package.  Create the database file if it doesn't exist.
 ...
 ...
 */
public abstract SQLiteDatabase openOrCreateDatabase(String name,
        int mode, CursorFactory factory);

Upvotes: 1

sabadow
sabadow

Reputation: 5151

The Context could be different but not create different DB's. The SQLiteOpenHelper constructor has a name parameter, that's the DB file name. If this exists will not create no matter the Context passed.

Upvotes: 2

Zsombor Erdődy-Nagy
Zsombor Erdődy-Nagy

Reputation: 16914

Pass in the Application context, (.getApplication()) instead of the Activity. That way, both instances will access the db using the same context.

Upvotes: 6

Related Questions