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

Android公交追踪应用传值为空:Double转换触发NumberFormatException

解决Android公交追踪应用的NumberFormatException空字符串问题

你遇到的java.lang.NumberFormatException: empty String错误,核心原因是传递到MapsActivity的经度(log)或纬度(lat)字符串为空,而Double.parseDouble()无法将空字符串转换为double类型。下面是分步解决方案:

一、在传递数据前添加输入校验

在启动MapsActivity之前,先检查用户输入的经纬度是否为空,同时验证格式是否合法,避免无效数据传递:

strack.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
        currselectedBus = busListArray.getSelectedItem().toString(); 
        new tracklat().execute(currselectedBus); 
        new tracklong().execute(currselectedBus); 

        // 获取并修剪输入内容,去除首尾空格
        String latInput = vtxtValidation.getText().toString().trim();
        String logInput = vtxtValidation2.getText().toString().trim();

        // 1. 检查是否为空
        if (latInput.isEmpty() || logInput.isEmpty()) {
            res.setText("请输入完整的经纬度!");
            return; // 终止后续流程,不跳转页面
        }

        // 2. 提前验证是否为有效数字
        try {
            Double.parseDouble(latInput);
            Double.parseDouble(logInput);
        } catch (NumberFormatException e) {
            res.setText("请输入有效的数字格式经纬度!");
            return;
        }

        // 验证通过后再传递数据
        res.setText("Tracking..."); 
        Intent intent = new Intent(getApplicationContext(), MapsActivity.class); 
        Bundle extras = new Bundle(); 
        extras.putString("bus", currselectedBus); 
        extras.putString("lat", latInput); 
        extras.putString("log", logInput); 
        intent.putExtras(extras); 
        startActivity(intent); 
    } 
});

二、在接收数据时做防御性处理

即使前面的校验出现遗漏,在MapsActivity中也要做容错处理,避免崩溃:

public void onMapReady(GoogleMap googleMap) { 
    Intent intent = getIntent(); 
    Bundle extras = intent.getExtras(); 

    // 先判断Bundle是否为空
    if (extras == null) {
        Toast.makeText(this, "未获取到有效数据", Toast.LENGTH_SHORT).show();
        return;
    }

    // 给参数设置默认值,避免null
    String busName = extras.getString("bus", "未知公交");
    String latStr = extras.getString("lat", "0.0").trim();
    String logStr = extras.getString("log", "0.0").trim();

    double latitude = 0.0;
    double longitude = 0.0;

    // 安全转换为double类型
    try {
        latitude = Double.parseDouble(latStr);
        longitude = Double.parseDouble(logStr);
    } catch (NumberFormatException e) {
        Toast.makeText(this, "经纬度格式错误,已使用默认坐标", Toast.LENGTH_SHORT).show();
    }

    mMap = googleMap; 
    LatLng location = new LatLng(latitude, longitude); 
    mMap.addMarker(new MarkerOptions().position(location).title(busName)); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(location)); 
}

额外提示

你代码中还有一个小细节:currselectedBus已经是String类型,不需要再调用.toString()方法,直接传递即可。

内容的提问来源于stack exchange,提问作者Tosan Ukuoritse

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:37:59