来自数据库的 Android 字符串资源

标签 android localization android-resources

我正在寻找一种解决方法来替换字符串资源 (strings.xml) 和 SQLite 表的内容。表的内容不断变化,并且与在线数据库同步。因此,当我在服务器上修改一些文本时,它们也应该在应用程序运行时进行更改。

我不想实用地设置每个 TextView 和其他文本,或创建自定义 TextView 等。

是否可以从该数据库表生成 xml 并将其用作字符串资源? (当然在运行时,生成的 xml 将与原始 xml 完全相同,除了字符串值,所以键不会改变) 或者有人有解决这个问题的想法吗?

最佳答案

无法即时更改 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;
    }
}

然后你可以像这样在 TextView 中使用它

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

这样您就可以更新数据库值并立即显示出来。更新数据库值时不要忘记清除 dbCache。这个解决方案显然不言而喻,数据库访问速度很慢,所以请记住这一点。

希望这对您有所帮助。

关于来自数据库的 Android 字符串资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21234931/

相关文章:

android - getIdentifier() 总是返回 0

java - 将日期时间转换为字符串,时间错误

java - 如何在android/Java中从xml获取属性值

java - 使用 Gson 将基类列表反序列化为派生类

angularjs - 如何从 angularjs 获取月份的本地化版本?

iphone - cocoa touch : Localized Application Randomly Changing Language

android - 如何从java代码中读取自定义维度属性

java - 将 EditText 格式化为带整数的货币

asp.net-mvc - ASP.NET MVC : When to set Thread. CurrentThread.CurrentUICulture?

android - 重建 Android Instant App 后,使用功能模块中基本模块中定义的颜色失败