2015-04-23 125 views
1

我有兩個數據庫來支持我的應用程序使用兩種語言。如何在Android中使用多種語言,如多種語言

我想在更改設置語言時更改數據庫。

有沒有可能?我怎樣才能做到這一點?

+0

你也可以創建一個名爲'translations'您存儲所有的名字之類的東西不同的表創建SQLite數據庫。例如,如果您有一個帶有'productid'的表'product'的表'product_translations',並帶有'productid','languagekey'和翻譯列。 (只是我過去做過的一種方式) – Bram

+0

你的意思是使用一個數據庫? – Hades10

+0

是的,我只使用了一個數據庫,只有2個表。 – Bram

回答

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,u需要自己創建數據庫,放入資產/數據庫文件夾。

你可以用這個程序Sqlitebrowser

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) { 
     // ... 
    } 

    // ... 
} 
+0

我會試試看。但我有一個小問題。我用這個鏈接預加載的數據庫:[android sqlite資產助手](https://github.com/jgilfelt/android-sqlite-asset-helper)。你能告訴我怎麼做嗎? – Hades10

+0

你爲什麼不問@MBH,誰接受了(這是我的副本)你接受了? – Ridcully