Android Studio中Activity间传递double值仅显示默认值0.0问题求助
问题排查及修复方案
1. 首要排查:Intent Extra 键值不匹配
这是该场景下90%以上问题的根因:Android Intent 传递参数时对Key的大小写、字符完全敏感,只要主Activity putExtra() 用的Key和第二个Activity getDoubleExtra() 用的Key存在任何不一致,系统会直接返回你设置的默认值0.0。
示例错误场景:主Activity用Key
"transfer_double",第二个Activity误写为"TransferDouble"/"transfer_doble"都会触发该问题。
2. 次位排查:输入转Double逻辑异常
检查主Activity中把EditText输入转Double的代码是否存在异常:
- 空输入未处理,直接调用
Double.parseDouble()触发NumberFormatException,后续默认赋值0.0 - 输入非数值格式内容,异常被捕获后返回默认值
推荐转换代码:
// 取输入框内容并去首尾空格 String inputContent = etInput.getText().toString().trim(); double targetValue = 0.0; if (inputContent.length() > 0) { try { targetValue = Double.parseDouble(inputContent); } catch (NumberFormatException e) { Toast.makeText(MainActivity.this, "请输入合法数字", Toast.LENGTH_SHORT).show(); return; } } // 确认转换后的值正确后再跳转 Log.d("TransferDebug", "准备传递的Double值:" + targetValue); Intent intent = new Intent(MainActivity.this, SecondActivity.class); intent.putExtra("统一的Key字符串", targetValue); startActivity(intent);
3. 末位排查:取值Intent对象错误
检查第二个Activity中取值时是否用了getIntent()返回的系统传递的Intent对象,不要手动new新的Intent取值,新创建的Intent不存在任何附加参数,只会返回默认值。
正确取值代码:
// 取系统传递过来的Intent Intent receivedIntent = getIntent(); double receivedValue = receivedIntent.getDoubleExtra("和主Activity完全一致的Key字符串", 0.0); Log.d("ReceiveDebug", "收到的Double值:" + receivedValue);
内容的提问来源于stack exchange,提问作者Mohammad Shatila
相关产品推荐
相关产品推荐

