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

Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top