w2lame
w2lame

Reputation: 2813

NullPointerException in Android application working on GPS

I have the following very simple class which looks for the last known user coordinates and then prints one of them. But I am getting loc as null variable. The application is not reading the data into the loc variable.

    import android.app.Activity;
    import android.content.Context;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.widget.Toast;

    public class Navigation extends Activity
    {
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        /* Use the LocationManager class to obtain GPS locations */
        try
        {
            LocationManager mlocManager = 
              (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Toast.makeText(getBaseContext(), 
                  "Provider Enable Status : " + mlocManager.isProviderEnabled(                       
                   mlocManager.getProvider("gps").getName()),     
                   Toast.LENGTH_LONG).show();

            Location loc = mlocManager.getLastKnownLocation("gps");
            Toast.makeText( getApplicationContext(), "" + 
                loc.getLatitude(),  Toast.LENGTH_LONG).show();
            Toast.makeText( getApplicationContext(), "" + loc,
                Toast.LENGTH_LONG).show();
         } catch (Exception e) {
           Toast.makeText(getBaseContext(), e.getMessage() + 
             e.toString(), Toast.LENGTH_LONG).show();
         }
      }
   }

I have added the following listener to the code :

        LocationListener mlocListener = new MyLocationListener();

        mlocManager.requestLocationUpdates( mlocManager.getProvider("gps").getName(), 0, 0, mlocListener);

in the oncreate function. And the following as a class in

public class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {
        Toast.makeText( getApplicationContext(),
            "Hi, location changed. :)", Toast.LENGTH_LONG).show();
        try {
        loc.getLatitude();
        loc.getLongitude();
        String Text = "My current location is: " +
                " Latitude = " + loc.getLatitude() +
                " Longitude = " + loc.getLongitude();
        Toast.makeText(getApplicationContext(),
                Text, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), 
                e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}

And after running the window, I do the following: go to DDMS in the Eclipse and set the lattitudes/longtitude and click on the send.

Still it doesn't fire any toast command in the function.

Upvotes: 3

Views: 2405

Answers (4)

Octavian Helm
Octavian Helm

Reputation: 39604

What WarrenFaith and djechelon said is indeed a good practice. Before using that object you should check for it not being null.

Also consider that if you are inside your activity there is no real need to get the context be calling getApplication() and getBaseContext(). Substitute them with this instead and try again.

You might also want to check your third Toast notification since you are settings its text to be ""+loc I guess you meant ""+loc.getLongitude().

If you need to have you activity's context somewhere in another class then define the context like this.

private Context ctx = null;

public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    // some code

    ctx = getApplication();

    // some more code

}

// your other class in the same Java file (inner class)

public class MyOtherClass {
    // a construtctor probably
    // some usefull methods
    Toast.makeText(ctx, "My message", 5000).show();
}

Upvotes: 1

Shardul
Shardul

Reputation: 786

Well you can do the null check, Thats absolutely fine approach to this issue. Another trick to this is on your onResume() call of activity you request location updates with :

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f,this);
    super.onResume();
}

In your case mlocManager, make sure you create this as an instance variable (class-level) and not local (not defined in method, in your case in onCreate).

This will surely fetch location updates and not throw null pointer. Also make sure you geofix your GPS configured emulator. Use DDMS's Emulator Control flyout to do that. fix some longitude and latitiude values before launching you activity.

Hope this helps!

Upvotes: 0

WarrenFaith
WarrenFaith

Reputation: 57672

Which makes sense... because if the device never had a known location, you can't get one. You should handle the null by yourself. Provide a new Location or wait for the first GPS data...

Upvotes: 1

usr-local-ΕΨΗΕΛΩΝ
usr-local-ΕΨΗΕΛΩΝ

Reputation: 26874

If you read the manual, it's explicitly said that the method returns "the last known location for the provider, or null".

I'm no Android developer, but I guess that it returns null on GPS cold boot until a fix has been made. You have to check that loc is !=null before continuing. You might try to wait some time or use an async callback.

Hope to have been of help.

Upvotes: 1

Related Questions