我一直在为我的应用程序进行本地化,但似乎找不到任何有关如何处理来自不同本地的十进制值和日期以存储在 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/