0

im attempting to get the location of a device into my android app. i have attempted to use the guide outlined on the android developer website however whenever i run the code on my phone the app stops straight away. my code is:

public class MainActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener{

    protected static final String TAG = "MainActivity";

    protected GoogleApiClient mGoogleApiClient;

    protected Location mLastLocation;
    protected Double lonValue;
    protected Double latValue;

    protected String mLatitudeLabel;
    protected String mLongitudeLabel;
    protected TextView mLatitudeText;
    protected TextView mLongitudeText;

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

        TextView lonView = (TextView) findViewById(R.id.lon);

        buildGoogleApiClient();

        //connect to parse backend
        Parse.initialize(this, "xxxx", "xxxx");
        ParseInstallation.getCurrentInstallation().saveInBackground();
        Log.d("myInstallation Id", ParseInstallation.getCurrentInstallation().getInstallationId());

        //get location
        lonValue = mLastLocation.getLatitude();
        latValue = mLastLocation.getLongitude();

        //text update

    }

    public void openLocation(View v){
        startActivity(new Intent(MainActivity.this, LocationActivity.class));
    }

    @Override
    public void onConnected(Bundle bundle) {

        //check build version on phone
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //check that app has permission to access data
            if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                //get information from location service
                mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                Log.d(TAG,mLatitudeLabel);
            }
        }

        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);


        // Provides a simple way of getting a device's location and is well suited for
        // applications that do not require a fine-grained location and that do not need location
        // updates. Gets the best and most recent location currently available, which may be null
        // in rare cases when a location is not available.

        buildGoogleApiClient();

        Toast.makeText(MainActivity.this, "Should have network", Toast.LENGTH_SHORT).show();
    }

    /**
     * Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
     */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }


    @Override
    public void onConnectionSuspended(int cause) {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }

}

logcat

02-28 18:45:08.848 4048-4048/com.worcestercomputing.ryanlambert.toiletstall E/AndroidRuntime: FATAL EXCEPTION: main Process: com.worcestercomputing.ryanlambert.toiletstall, PID: 4048 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.worcestercomputing.ryanlambert.toiletstall/com.worcestercomputing.ryanlambert.toiletstall.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference at com.worcestercomputing.ryanlambert.toiletstall.MainActivity.onCreate(MainActivity.java:63) at android.app.Activity.performCreate(Activity.java:6251) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

7
  • could you please post the logcat too..
    – Lal
    Feb 28, 2016 at 18:42
  • Are you running it on an emulator? You have to pass latitude and longitude separately for location to work on the emulator. Moreover, in real life situations, getLastLocation can sometimes return null (user might have disabled location from the day he bought the phone), and therefore you should implement a null check.
    – rick
    Feb 28, 2016 at 18:52
  • im running on a physical device. how could i implement a null check on this? (sorry, only just learning the ropes) Feb 28, 2016 at 18:57
  • Using simple if/else statements will do. Check if mLastLocation is null or not, and use getLatitude only if it's not null. Also, Parse will be dead by this year end, you should replace it's functionality asap.
    – rick
    Feb 28, 2016 at 19:07
  • Implementing a location listener will make things really easy for you.
    – rick
    Feb 28, 2016 at 19:12

1 Answer 1

0

Obviously, the problem is that you call

//get location
lonValue = mLastLocation.getLatitude();
latValue = mLastLocation.getLongitude();

in Activity.onCreate(). But mLastLocation is still null at that time.

Note that onCreate(Bundle) is Activity lifecycle callback where you initialize the activity - it's the first thing to be called when a new instance of an Activity is created.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.