'After sending data from MainActivity to Fragment, the variables are setup to 0.0

I'm trying to pass from MainActivity to Fragments (by using ViewPager, and TabLayout, if it will help you anyhow) user's latitude, and longitude. The thing is, I receiving 0.0 in the fragment.

MainActivity

private void getUserLocation() {
        FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            checkPermissions();
        }
        fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {
                    mLatitude = location.getLatitude();
                    mLongitude = location.getLongitude();

                    Bundle args = new Bundle();
                    args.putDouble("lat", mLatitude);

                    TestFragment fragment = new TestFragment();
                    fragment.setArguments(args);
                }
            }
        });
        test();
    }

Inb4 - the mLongitude, and mLatitude variables contains proper data in MainActivity

Fragment

    public class TestFragment extends Fragment {
    public static final String TAG = "TestFragment";
    private double mLatitude, mLongitude;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle bundle = this.getArguments();
        if (bundle != null) {
            mLatitude = bundle.getDouble("lat");
            Log.i(TAG, "onCreateView: " + mLatitude);
        }
        return inflater.inflate(R.layout.fragment_test, container, false);
    }
}

How I may solve it?



Solution 1:[1]

It seems like you are not using that particular fragment object you declared in onSuccess, in which you passed that bundle object.

In Fragment you get 0.0 because that's the default value of getDouble method of Bundle class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saad Tariq