Reputation: 6815
If multiple activities within an app call the constructor of my SQLiteOpenHelper with themselves as the context argument, can I be sure that they will all access the same database?
For example, let's say I have:
package foo.bar;
public class Activity1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SQLiteDatabase db = new MySQLiteOpenHelper(this).getReadableDatabase();
:
}
}
and
package foo.bar.baz;
public class Activity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SQLiteDatabase db = new MySQLiteOpenHelper(this).getReadableDatabase();
:
}
}
Here's in the skeleton of my SQLiteOpenHelper subclass:
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "comments.db";
private static final int DATABASE_VERSION = 1;
public MySQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
:
}
I can't find anything in the documentation that guarantees that the two activities get the same database. On the other hand, I haven't seen any mentions of people getting different databases from contexts within a single application. Are the database paths guaranteed to be identical?
Upvotes: 1
Views: 91
Reputation: 43023
SQLiteOpenHelper
has 2 constructors and the second parameter for both of them is the database file name.
If you used the same database file name when using SQLiteOpenHelper
from different activities, you will get access to the same database.
This is usually taken care of in the constructor of the inheriting class you create - DATABASE_NAME
is a constant:
public MySQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Upvotes: 1
Reputation: 4846
if you do it as the Android folks recommend (http://developer.android.com/guide/topics/data/data-storage.html#db)
Then yes, all activities within an app will see the same database
Upvotes: 1