2014-01-20 54 views
3

我正在尋找一種解決方法來替換SQLite表的內容的字符串資源(strings.xml)。該表的內容正在改變,並且在線數據庫。所以,當我修改服務器上的一些文本時,它們應該在運行時也在應用程序中進行更改。來自數據庫的Android字符串資源

我不想設定每一個TextView中的其它文本務實,或者創建自定義的TextView等

是否有可能從該數據庫表生成XML並把它作爲字符串資源? (當然運行時間和生成的XML將與原始完全相同,除了字符串值,所以鍵不會改變) 或者有沒有人有想法解決這個問題?

+0

不可能。當然,除非你的應用反編譯自己>用新值覆蓋strings.xml>重新編譯並將自身複製到'/ data/app /',然後強制重新啓動目標。 – ozbek

+0

好吧,那只是我的一個想法,但其他任何方式呢? – possenH4lt3r

回答

0

無法即時更改strings.xml文件。你可以做的是抽象字符串聚集。

class YourUtilites { 

    static HashMap<String, String> dbCache = new HashMap<String, String>(); 
    public static String getString(Context context, String key, String defaultID) { 
     String value = null; 

     value = dbCache.get(key); 

     if (value == null) { 
      // Check if the key exists in the database 
      String value = db.somedbFunctionToGetString(key); 
      if (value != null) { 
       dbCache.put(key, value); 
      } 
     } 

     if (value == null) { 
      // If value is not in the database, resort to the default value 
      value = context.getResources().getString(defaultID); 
     } 

     return value; 
    } 
} 

然後你就可以在textviews使用這樣

textView.setText(YourUtilities.getString("dbKey", R.id.defaultValue1, this); 
textView2.setText(YourUtilities.getString("dbKey2", R.id.defaultValue2, this); 
... 

這樣你就可以更新你的分貝值,並將它立刻顯示出來。當您更新數據庫值時,不要忘記清除dbCache。這個解決方案顯然不用說db訪問速度慢,所以記住這一點。

希望這會有所幫助。