Milan CAMUS
Milan CAMUS

Reputation: 23

Get current latitude and longitude in fragment

I tried to get my current GPS coordinates in a fragment, but it does not work. Here is my code:

public class AjouterBancFragment extends Fragment {

    TextView textViewLongLat;
    LocationManager locationManager;
    String provider;
    Location location;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.ajouter_banc, container, false);

        textViewLongLat = v.findViewById(R.id.textViewLongLat);

        // Déclarations
            // Bouton
            Button buttonAdd = v.findViewById(R.id.buttonAjouterBanc);

            buttonAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    locationManager =(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
                    Criteria c=new Criteria();
                    //if we pass false than
                    //it will check first satellite location than Internet and than Sim Network
                    provider=locationManager.getBestProvider(c, false);
                    if ((ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
                        location=locationManager.getLastKnownLocation(provider);
                    }

                    if(location!=null)
                    {
                        double lng=location.getLongitude();
                        double lat=location.getLatitude();
                        textViewLongLat.setText("Position actuelle : "+lat+","+lng);
                    }
                    else
                    {
                        textViewLongLat.setText("No Provider");
                    }
                }
            });
        return v;
    }
}

The problem is that this code gives me my coordinates of a place where I was 2 days ago. Thank you.

Upvotes: 0

Views: 2802

Answers (2)

Milan CAMUS
Milan CAMUS

Reputation: 23

I tried another method because I did not really understand how "requestSingleUpdate" works So I looked at some tutorials to use "requestLocationUpdates", but the problem is that it doesn't work either. Here's my new code :

// All import stuffs

public class AjouterBancFragment extends Fragment {

    TextView textViewLongLat;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.ajouter_banc, container, false);

        textViewLongLat = v.findViewById(R.id.textViewLongLat);
        Button buttonAdd = v.findViewById(R.id.buttonAjouterBanc);

        buttonAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
                    LocationListener locationListener = new AjouterBancFragment.MyLocationListener();
                    if ((ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
                        Toast.makeText(getContext(), "OK", Toast.LENGTH_SHORT).show();   // Toast is showing
                    }

                }
            });
        return v;
    }

    private class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {
            Toast.makeText(getContext(), "OnLocationChanged", Toast.LENGTH_SHORT).show();   // Toast not showing
            String longitude = "Longitude: " + loc.getLongitude();
            String latitude = "Latitude: " + loc.getLatitude();
            String s = longitude + "\n" + latitude;
            textViewLongLat.setText(s);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Toast.makeText(getContext(), "onProviderDisabled", Toast.LENGTH_SHORT).show();  // Toast not showing
        }

        @Override
        public void onProviderEnabled(String provider) {
            Toast.makeText(getContext(), "on ProviderEnabled", Toast.LENGTH_SHORT).show();  // Toast not showing
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Toast.makeText(getContext(), "onStatusChanged", Toast.LENGTH_SHORT).show();  // Toast not showing
        }
    }
}

I put Toast Message in order to see the steps of my code, but I only have one Toast Message that appears (it is annotated in the code). If anyone has an idea why it doesn't work, I'm interested ! Thanks you.

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93559

Don't use getLastKnownLocation. Use requestSingleUpdate, which will turn on your GPS and find out your current location before sending you a callback.

Upvotes: 1

Related Questions