Question

I use android sdk on eclipse and i want to get location from device so i wrote an program in other class(diffrent from main) and i call mContext function inside this class from main class:

package com.example.deomanapp;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.example.deomanapp.MainActivity.PlaceholderFragment;

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

public class Mhelper {

    public void mContext(Context context)
    {
        LocationManager lm;
        lm   = (LocationManager)context.getSystemService(context.LOCATION_SERVICE); 
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        String slongitude = String.valueOf((long) longitude);
        String slatitude = String.valueOf((long) latitude);

        Toast.makeText(context, slongitude, Toast.LENGTH_SHORT).show();

    }

}

The problem is getLongitude or getLatitude return null,so the program crash on this line with this log:

04-20 04:30:30.410: E/AndroidRuntime(5151): java.lang.NullPointerException
04-20 04:30:30.410: E/AndroidRuntime(5151):     at com.example.deomanapp.Mhelper.mContext(Mhelper.java:29)

What is wrong with this code ?

PS: I read other question with the same title and non of theme help (non of them have actual answer) because:

1-I test this program on the real device(not emulator) with GPS ON and working , but this program can't able to get location although the Device get its location before and it must show LastKnownLocation.

2-I gave the program ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permission.

3-I even use an function to see if the GPS is on, when i turn it off program alert me.

Was it helpful?

Solution

It was silly question to ask ,It was null because it was NULL,i understand it by comments on main question, my solution was to download android api image in sdk manager,run Google map once and send GPS location to it by DDMS and then run the program.

OTHER TIPS

I have tried to modify some of my code, hopefully it works for your needs.

You will find the implementation of my LocationsCoreModule code in the bottom of the answer:

LocationsCoreModule locationService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LocationRequest mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(5000);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(1000);

    locationService = new LocationsCoreModule(this, mLocationRequest);
    locationService.setLocationsListener(new LocationsCoreModuleCallback() {

        @Override
        public void locationClientConnected() {
              Location location = locationService.getLastLocation();
              double longitude = location.getLongitude();
              double latitude = location.getLatitude();
              String slongitude = String.valueOf((long) longitude);
              String slatitude = String.valueOf((long) latitude);

              Toast.makeText(getApplicationContext(), slongitude, Toast.LENGTH_SHORT).show();
        }
    });
}

If you want the application to start listening for new GPS locations right away:

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

    locationService.start(new LocationListener() {

        @Override
        public void onLocationChanged(Location arg0) {
            // TODO Auto-generated method stub

        }
    }, new OnConnectionFailedListener() {

        @Override
        public void onConnectionFailed(ConnectionResult arg0) {
            // TODO Auto-generated method stub

        }
    });
}

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

    locationService.stop();
}

And finally, the LocationsCoreModule:

public class LocationsCoreModule implements
        GooglePlayServicesClient.ConnectionCallbacks {

    private static final String TAG = "LocationsCoreModule";

    public interface LocationsCoreModuleCallback {
        public void locationClientConnected();
    }

    private LocationsCoreModuleCallback locationsCoreModuleCallback;

    private com.google.android.gms.location.LocationListener locationListener;

    private Location lastLocation;

    private LocationClient mLocationClient;

    private final LocationRequest mLocationRequest;
    private final Context context;


    @Inject 
    public LocationsCoreModule(Context context, LocationRequest locationRequest) {
        this.context = context;
        this.mLocationRequest = locationRequest;


    }

    public void setLastLocation(Location lastLocation) {
        this.lastLocation = lastLocation;
    }

    public void setLocationsListener(
            LocationsCoreModuleCallback locationsCoreModuleCallback) {
        this.locationsCoreModuleCallback = locationsCoreModuleCallback;
    }

    public void start(
            com.google.android.gms.location.LocationListener locationListener,
            GooglePlayServicesClient.OnConnectionFailedListener connectionFailedListener) {
        this.locationListener = locationListener;
        mLocationClient = new LocationClient(context, this,
                connectionFailedListener);
        mLocationClient.connect();
    }

    public void stop() {
        if (mLocationClient != null) {
            // If the client is connected
            if (mLocationClient.isConnected() && locationListener != null) {
                /*
                 * Remove location updates for a listener. The current Activity
                 * is the listener, so the argument is "this".
                 */
                mLocationClient.removeLocationUpdates(locationListener);
            }

            // Disconnecting the client invalidates it.
            mLocationClient.disconnect();
        }
    }


    public boolean isConnected() {
        if (mLocationClient == null) return false;
        return mLocationClient.isConnected();
    }

    public Location getLastLocation() {

        if (lastLocation != null) {
            return lastLocation;
        }

        if (mLocationClient != null) {
            if (mLocationClient.isConnected()) {
                return lastLocation = mLocationClient.getLastLocation();
            }

            if (!mLocationClient.isConnecting())
                mLocationClient.connect();
        }

        return null;

    }

    @Override
    public void onConnected(Bundle connectionHint) {
        Log.d(TAG, "GooglePlayServices connected!");

        Location lastLocation = mLocationClient.getLastLocation();

        if (lastLocation == null)
            Log.e(TAG, "Lastlocation is null even after connected!!!!");

        if (locationsCoreModuleCallback != null) {
            locationsCoreModuleCallback.locationClientConnected();
            locationsCoreModuleCallback = null; // single shot
        }

    }

    public void requestLocationUpdates() {
        if (mLocationClient != null && mLocationClient.isConnected()) {
            Log.d(TAG, "Requesting location updates");
            mLocationClient.requestLocationUpdates(mLocationRequest,
                    locationListener);
        }
    }

    public void stopLoactionUpdates() {
        if (mLocationClient != null && mLocationClient.isConnected()) {
            mLocationClient.removeLocationUpdates(locationListener);
        }
    }

    @Override
    public void onDisconnected() {
        Log.d(TAG, "GooglePlayServices disconnected!");
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top