Home » Android » java – Android – double values aren't saved-Exceptionshub

java – Android – double values aren't saved-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a weird problem with my latitude, longitude values.

At first, I started them with -1. Then, at the listeners, they changed to the

correct values, but something really strange happened. when I checked the

latitude, longitude of the latlng, it said me that they are -1. How is it

possible? they were correct at the listeners, and I didn’t change them.

double latitude = -1, longitude = -1;

private void createMarkers() {

        user_Fb = FirebaseAuth.getInstance().getCurrentUser();
        database = FirebaseDatabase.getInstance();
        mDatabaseRef = database.getReference();

        mDatabaseRef.child("users").child(user_Fb.getUid()).child("latitude").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                latitude =  dataSnapshot.getValue(double.class);     //XX.XXXX
                Log.d("loc_TAG", "latitude " + latitude);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        mDatabaseRef.child("users").child(user_Fb.getUid()).child("longitude").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                longitude = dataSnapshot.getValue(double.class);      //XX.XXXX
                Log.d("loc_TAG", "longitude " + longitude);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });

        LatLng our_location = new LatLng(latitude, longitude);
        Log.d("loc_TAG", "latitude " + our_location.latitude);     //-1.0
        Log.d("loc_TAG", "longitude " + our_location.longitude);   //-1.0
        mMap.addMarker(new MarkerOptions().position(our_location).title(user_Fb.getPhoneNumber()));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(our_location, 12.0f));
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    }
How to&Answers:

Check the values right before new LatLng(latitude, longitude) and the “new LatLng” return.
The lat and long values change only when triggers listener, maybe the instantiation is running before the listener.