java - Android 本地化查询

标签 java android localization number-formatting

我一直在为我的应用程序进行本地化,但似乎找不到任何有关如何处理来自不同本地的十进制值和日期以存储在 sqllite 中的信息。

例如: 德国十进制 123,53 英国十进制 123.53

那么如何从编辑文本字段转换为有效的小数。目前,我的代码输出到 TextView 而不是 sql 只是为了测试。下面的代码在使用英国十进制时效果很好,但如果我使用德国十进制,它就会失败!!

 Configuration sysConfig = getResources().getConfiguration();
 Locale curLocale = sysConfig.locale;
 NumberFormat nf = NumberFormat.getInstance(curLocale);
 String convertedString = nf.format(Double.parseDouble(EditTextField.getText().toString()));

 TextView showLocalisedNumeric;
 showLocalisedNumeric = (TextView)findViewById(R.id.TestNumericValue);
 showLocalisedNumeric.setText(convertedString);

我还没有开始使用日期,但我假设将日期转换为更直接。

最佳答案

经过一段时间的研究,我找到了本地化的解决方案,从输入中获取值并将其解析为 SQLlite 可以理解的格式 - 对于此练习并为了减少代码,我刚刚将其设置为输出到 TextView 。

 // set initial value to variables
    String convertedString = "";
    double parsedValue = 0.0;

    //get value from text field
    EditText EditTextField  =(EditText)findViewById(R.id.TestNumericValueEntered);
    String valueFromInput = EditTextField.getText().toString();

    //Get current Locale from system
    Configuration sysConfig = getResources().getConfiguration();
    Locale curLocale = sysConfig.locale;

    //Set number formats
    NumberFormat nf_in = NumberFormat.getNumberInstance(curLocale);
    NumberFormat nf_out = NumberFormat.getNumberInstance(Locale.UK);

    //try to parse value, otherwise return error message
    try {
        parsedValue = nf_in.parse(valueFromInput).doubleValue();
        // use nf_out.setMaximumFractionDigits(3) to set max number of digits allowed after decimal;
        convertedString = nf_out.format(parsedValue);
    }catch(ParseException e){
        convertedString = "Unable to translate value";
    }
    //Output result
    TextView showLocalisedNumeric;
    showLocalisedNumeric = (TextView)findViewById(R.id.TestNumericValue);
    showLocalisedNumeric.setText(convertedString);

当我添加这个答案时,我意识到对代码的一个很好的补充是检查当前区域设置是否与您计划解析的区域设置相同,如果是这样,则可以跳过转换(解析)。

关于java - Android 本地化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27837689/

相关文章:

java - Android - getApplicationContext 出错

.net - 对于可插拔组件的本地化,这是一个很好的解决方案吗?

ios - 使用 secureTextEntry 为 UITextField 选择键盘语言

java - 文件显然无法转换为文件

java - 将字符串转换为 AES 的 128 位 key

java - 有什么方法可以在构造函数中嵌入代码,该构造函数将在所有子类的构造函数代码之后运行?

android - 根据android中的使用情况对应用程序进行排序

android - Gradle同步失败,并且灰色文件

java - 如何将 log4j 设置为每个错误/警告/信息的特定文件(在 grails 中)

python - 在 Windows 上设置 Python 语言环境的正确方法是什么?