Are all databases provided by a SQLiteOpenHelper constructed with the same name within an app guaranteed to be identical?

StackOverflow https://stackoverflow.com/questions/22212123

문제

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?

도움이 되었습니까?

해결책

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);
}

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top