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

Android中如何将第一个setOnClickListener获取的经纬度传递到第二个并存入Firestore

你遇到的Cannot resolve symbol 'address'报错是因为address是第一个点击监听器onClick方法内的局部变量,作用域仅局限于该方法内部,第二个点击监听器的代码块无法跨作用域访问该变量。

解决方案

1. 在Activity/Fragment类中声明全局成员变量

在类内部、所有方法之外声明变量存储经纬度,同时增加标记位判断是否获取到有效地址,避免后续空指针异常:

// 类成员变量
private double eventLatitude = 0.0;
private double eventLongitude = 0.0;
private boolean isLocationValid = false;

2. 修改搜索按钮的点击逻辑,获取地址后给成员变量赋值

searchLoc.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Geocoder geoceoder = new Geocoder(getApplicationContext(), Locale.getDefault());
        try{
            List<Address> addressList = geoceoder.getFromLocationName(locationName, 3);

            if(addressList.size() > 0){
                Address address = addressList.get(0);
                // 给全局变量赋值
                eventLatitude = address.getLatitude();
                eventLongitude = address.getLongitude();
                isLocationValid = true;
                goToLocation(eventLatitude, eventLongitude);
                // 其余原有代码保持不变
                ...
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

3. 修改创建事件按钮的点击逻辑,直接使用成员变量

注意你原有代码中getLatitude是方法,需要加括号调用,同时增加地址有效性校验:

create_eventBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // 校验是否已经获取有效地址
        if (!isLocationValid) {
            // 替换为你当前Activity的实例
            Toast.makeText(YourActivity.this, "请先搜索选择有效地址", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String,Object> event = new HashMap<>();
        event.put("eventLocationLat", eventLatitude);
        event.put("eventLocationLong", eventLongitude);
        fStore.collection("event").add(event);
        // 其余原有代码保持不变
        ...
    }
});

内容的提问来源于stack exchange,提问作者PI PI NAN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:27:03