How does it work SQLiteOpenHelper Context
Asked Answered
D

3

8

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.

Davide answered 9/11, 2012 at 12:34 Comment(0)
S
6

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

Sealer answered 9/11, 2012 at 12:37 Comment(0)
V
2

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.

Variform answered 9/11, 2012 at 12:40 Comment(1)
Context is an interface for accessing system resources. As mentioned by sabadow, which database is determined by name.Dicot
R
1

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);
Resolvable answered 15/2, 2016 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.