You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:48:00