0

I am a begginer in Android programming and I encountered a problem with displaying the current location of my phone using the NETWORK PROVIDER, with which I need some help.

Here is the code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtLat = (TextView) findViewById(R.id.txtLat);
    txtLon = (TextView) findViewById(R.id.txtLon);

    Log.d("ADebugTag",  "WTF");

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            txtLat.setText(String.valueOf(location.getLatitude()));
            txtLon.setText(String.valueOf(location.getLongitude()));
        }

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

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
      };
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    Log.d("ADebugTag",  "WTF END");
}   

I try to set the latitude and longitude of the location into the TextViews, but my app crashes when i try tu run it. Also, I tried to print a full stack trace, but I couldn't find a method to make it work..

UPDATE: Thanks for all the replies :D - After posting this I realized I should have also posted the layout of the main activity, just in case.

<TextView
    android:id = "@+id/txtLat"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:text="LATITUDINE" />
<TextView
    android:id = "@+id/txtLon"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/txtLat"
    android:text="LONGITUDINE" />

Also, I have tried to print something in logcat when the onLocationChanged method gets called, but the message is not displayed when I run the app, meaning that the method is not called. I am running this app on an older device, using Android 2.3.6, maybe that is useful information as well.

FaneDD
  • 1
  • 1
  • Pretty sure that the LocationManager methods should be declared outside of onCreate – jesses.co.tt Jul 27 '15 at 17:57
  • 3
    *Also, I tried to print a full stack trace, but I couldn't find a method to make it work..* Copy & Paste works just fine. – Machado Jul 27 '15 at 17:57
  • also, the requestLocationUpdates (and a matching removeUpdates() call) should go in onResume and onPause resepectivley – jesses.co.tt Jul 27 '15 at 17:59
  • check this http://stackoverflow.com/a/31573421/4987172 – Rene Limon Jul 27 '15 at 18:00
  • 1
    Have you requested the required permission? *ACCESS_COARSE_LOCATION* or *ACCESS_FINE_LOCATION* – Sascha Kolberg Jul 27 '15 at 18:00
  • Thanks for all the replies! I have declared LocationManager outside on the onCreate method, I have added onResume with the requestLocationUpdates and I have both permissions in my manifest and still it isn't displaying the current longitude or latitude.Still, I will try more methods to make it work :D – FaneDD Jul 28 '15 at 18:50

3 Answers3

1

It's highly possible that you are lacking the corresponding app rights. Make sure you added following lines to your manifest file:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I am not sure about the first 2, but for sure you must have the coarse and fine location permissions.

  • Thanks for the reply! I already had the last two lines added to my manifest, and I added the first two now, but still it isn't displaying the latitude or longitude – FaneDD Jul 28 '15 at 18:52
0

Here's an example that I reuse in m apps, using a custom class to wrap the LocationListener:

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;


public class MyLocationListener implements LocationListener {

  // GLOBALS
  float currentLatitude     = 0;
  float currentLongitude    = 0;
  float currentAltitude     = 0;
  float currentAccuracy     = 0;
  float currentSpeed        = 0;
  float currentBearing  = 0;
  String currentProvider    = "";

  public MyLocationListener(Context context) {
        super();
  }

  // Define all LocationListener methods
  public void onLocationChanged(Location location) {

    currentLatitude  = (float)location.getLatitude();
    currentLongitude = (float)location.getLongitude();
    currentAltitude = (float)location.getAltitude();
    currentAccuracy  = (float)location.getAccuracy();
    currentSpeed = (float)location.getSpeed();
    currentBearing = (float)location.getBearing();
    currentProvider  = location.getProvider();

  }

  public void onProviderDisabled (String provider) { 
    //currentProvider = "";
    Log.v(TAG, "Provider is " + provider);
  }

  public void onProviderEnabled (String provider) { 
    //currentProvider = provider;
    Log.v(TAG, "Provider is " + provider);
  }

  public void onStatusChanged (String provider, int status, Bundle extras) {
    Log.v(TAG, "Status is " + status);
  }

  // Custom Methods

  public String getCurrentLatitude() {
      String lat = Float.toString(currentLatitude);
      return lat;
  }

  public String getCurrentLongitude() {
      String lon = Float.toString(currentLongitude);
      return lon;
  }

  public String getCurrentAltitude() {
      String alt = Float.toString(currentAltitude);
      return alt;
  }

  public String getCurrentAccuracy() {
      String acc = Float.toString(currentAccuracy);
      return acc;
  }

  public String getCurrentSpeed() {
      String spd = Float.toString(currentSpeed);
      return spd;
  }

} 

... and then in onCreate

// GPS
        locationListener = new MyLocationListener(this); // instance of above class

// Runnable
        handler = new Handler();
        runnable = new Runnable() {
            public void run() {
                handler.postDelayed(this, REFRESH_RATE);

                // Get Data

                float lat = Float.parseFloat(locationListener.getCurrentLatitude());
                float lon = Float.parseFloat(locationListener.getCurrentLongitude());



                // Update Text
                ActualLatitude.setText(locationListener.getCurrentLatitude());
                ActualLongitude.setText(locationListener.getCurrentLongitude());

            }
        };
        handler.postDelayed(runnable, REFRESH_RATE);

.. and then in onResume

@Override
protected void onResume() {
    super.onResume();

    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, REFRESH_RATE, 5, locationListener);
    locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}

.. and then in onDestroy

@Override
public void onDestroy() {
    super.onDestroy();

    // Kill Runnable
    handler.removeCallbacks(runnable);

    // Stop GPS
    locationManager.removeUpdates(locationListener);
    locationManager = null;

}

Some other notes:

  • make sure you have requested the COARSE_LOCATION and/or FINE_LOCATION in your AndroidManifest
  • double check the id's of your textviews - you said it was crashing and without seeing a stacktrace, for all we know the location stuff is fine but its crashing on a NPE!
jesses.co.tt
  • 2,689
  • 1
  • 30
  • 49
0

Here is my current working code for getting user location in android:

public class MyApp extends Application{
   private LocationManager locationManager;
   private LocationListener listener;

   @Override public void onCreate(){ 
       super.onCreate(); 
   }

   public void acquireUserCoordinates(){

    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){

        listener = new GpsListener();

        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);

    }else {
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

            listener = new GpsListener();

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);

        }
    }

  }

  private class GpsListener implements LocationListener {

    public void onLocationChanged(Location location) {
        if (location != null) {

            double mLatitude = location.getLatitude();
            double mLongitude = location.getLongitude();

            EventBus.getDefault().post(new UserLocationAcquiredEvent(true, mLatitude, mLongitude));


            try {
                if (listener != null)
                    locationManager.removeUpdates(listener);
            } catch (Exception e) {
            }

            locationManager = null;

        } else {

        }

    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
  }

}

Now, you notice that I use EventBus library here to post results to the respective activity/fragment.

In your activity or fragment, you get the application instance (getApplication()) and call the acquireUserCoordinates() method then you can override onEvent(EventClassHere event) and then easily update the UI respectively (like dismiss dialog).

You can find EventBus here: EventBus

I hope this helps you.

Good luck and happy coding!

Eenvincible
  • 5,641
  • 2
  • 27
  • 46