Saboor880 9 Junior Poster

I have made a simple app which gets curren location (latitude and longitude). It is working perfectly. But now i want to take location updates. For this i implemented LocationListener interface .
I overridded the metod On location Change, but when i run the application, this method does not respond in any way. There is no error, no exception and no response I have attached my code. Please check it and guide me

        package com.example.hp430.gpslocaction;

  import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class ThirdActivity extends AppCompatActivity {
LocationManager locationManager;
TextView textView;
String latitude, longitude;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
    textView = findViewById(R.id.txtLoc);
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Please turn on your GPS connection").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

            }
        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
    });
        final AlertDialog alert = builder.create();
        alert.show();
    } else {
        Toast.makeText(this, "GPS is enabled", Toast.LENGTH_SHORT).show();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

            return;
        }
        locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
                5000,
                0, locationListenerGPS);

        } else {
            Toast.makeText(this, "Unable to trace your location", Toast.LENGTH_SHORT).show();
        }*/

    }

}

LocationListener locationListenerGPS=new LocationListener() {
    @Override
    public void onLocationChanged(android.location.Location location) {

        double latitude=location.getLatitude();
        double longitude=location.getLongitude();
        String msg="New Latitude: "+latitude + "New Longitude: "+longitude;
        Toast.makeText(ThirdActivity.this,msg,Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
 };

   }

Dani AI

Generated

a few things in your flow keep onLocationChanged from ever firing. You request the permission but never start updates after the user responds, and your check effectively blocks updates unless both FINE and COARSE are granted. Also, after sending the user to Settings to enable GPS you never re-register. Move the call to requestLocationUpdates() into a helper you invoke from onResume() and from onRequestPermissionsResult(). Add a NETWORK fallback so you get quick updates (and emulator data) even before GPS has a fix. Finally, clean up the extra else/*/ so the code path that starts updates is actually reachable.

Here is a small, drop-in pattern you can adapt:

private LocationManager lm;

private final LocationListener listener = new LocationListener() {
  @Override public void onLocationChanged(Location l) {
    Toast.makeText(ThirdActivity.this,
        "Lat:" + l.getLatitude() + " Lon:" + l.getLongitude(),
        Toast.LENGTH_SHORT).show();
  }
};

private void startLocationUpdates() {
  boolean fine = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
      == PackageManager.PERMISSION_GRANTED;
  boolean coarse = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
      == PackageManager.PERMISSION_GRANTED;

  if (!fine && !coarse) {
    ActivityCompat.requestPermissions(this,
        new String[]{ Manifest.permission.ACCESS_FINE_LOCATION }, 100);
    return;
  }

  lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  if (fine) lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, listener);
  lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, listener);
}

@Override protected void onResume() { super.onResume(); startLocationUpdates(); }
@Override protected void onPause()  { super.onPause();  if (lm != null) lm.removeUpdates(listener); }

@Override public void onRequestPermissionsResult(int code, String[] p, int[] r) {
  if (code == 100 && r.length > 0 && r[0] == PackageManager.PERMISSION_GRANTED) startLocationUpdates();
}

Tips: ensure the permission is in the manifest, test outdoors or with injected emulator location, and keep minTime/minDistance reasonable so you are not waiting too long between callbacks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.