Home > Net >  Failed to access Latitude and Longitude using address.getLatitude() in second setOnClickListener cod
Failed to access Latitude and Longitude using address.getLatitude() in second setOnClickListener cod

Time:09-28

May I ask, how can I get the latitude and longitude from the first setOnClickListener below and pass it to second setOnClickListener? I want to store the latitude and longitude in Firestore by using code in the second setOnClickListener. My idea is when I click on the Search Icon, the app will get the latitude and longitude of the location.Location Search

First setOnClickListener code

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){
                        //The address variable is declared in the first setOnClickListener.
                        Address address = addressList.get(0);
                        goToLocation(address.getLatitude(), address.getLongitude());
.
.
.
                        

Second setOnClickListener code

I failed to access the Latitude and Longitude via address.getLatitude() in second setOnClickListener block code. I get error: Cannot resolve symbol 'address'

create_eventBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String,Object> event = new HashMap<>();
                //Couldn't access the "address" in first setOnClickListener using address.getLatitude
                event.put("eventLocationLat", address.getLatitude);
                event.put("eventLocationLong", address.getLongitude);
                fStore.collection("event").add(event)...;
});

So, when the user press the "Create Event" button at the bottom, the second setOnClickListener will be executed and store the latitude and longitude inside the Firestore.

Add Event enter image description here

CodePudding user response:

You are getting the following error:

Cannot resolve symbol 'address'

Because you have declared the address object inside the scope of the first listener. This means that the object is not visible inside the second listener, hence the error.

To solve this, declare the variable as a member of the class:

private Address address;

Initilize it inside the first listener:

 address = addressList.get(0);

And then simply use it inside your second listener. The error will be gone.

  • Related