I have two database to support two languages for my application.
I want to change database when I change language from settings.
Is it possible?? How can i do this?
答案 0 :(得分:4)
当您提供具有数据库名称的字符串资源时,应该可以非常轻松:
在/res/values/strings.xml
中添加如下行:
<string name="db_name">database</string>
在/res/values-de/strings.xml
放置该行:
<string name="db_name">database_de</string>
在您的DBHelper类中,根据语言设置使用当前活动的字符串文件的数据库名称:
public class DBHelper extends SQLiteOpenHelper {
private final static int DB_VERSION = 1;
private static DBHelper sInstance;
/**
* Provides access to DBHelper singleton.
* @param context
* @return
*/
public static DBHelper getInstance(Context context) {
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
// See this article for more information: http://bit.ly/6LRzfx
if (sInstance == null) {
sInstance = new DBHelper(context.getApplicationContext());
}
return sInstance;
}
/**
* Constructor should be private to prevent direct instantiation.
* make call to static factory method "getInstance()" instead.
*/
private DBHelper(Context context) {
// here comes the magic:
String dbName = context.getString(R.string.db_name);
super(context, db_name, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// ...
}
// ...
}
答案 1 :(得分:0)
使用 Ridcully 解决方案,您只需要添加数据库名称部分, 您需要添加的就是您扩展的类。
这个例子来自你提到的图书馆:
public class MyDatabase extends SQLiteAssetHelper {
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
// here comes the magic:
String dbName = context.getString(R.string.db_name);
super(context, dbName , null, DATABASE_VERSION);
}
}
另一个数据库类可以是:
public class MyDatabase2 extends SQLiteAssetHelper {
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
// here comes the magic:
String dbName = context.getString(R.string.db_name_2);
super(context, dbName , null, DATABASE_VERSION);
}
}
注意:要使用SQLiteAssetHelper,您需要自己创建数据库,并放入assets / databases文件夹。
您可以使用此应用Sqlitebrowser
创建sqlite数据库