谷歌地图当前位置NullPointerException

时间:2014-06-28 06:32:23

标签: android maps

地图问题

我有这个代码来获取当前位置并将地图移动到该位置 但是这段代码有时会显示我之前所处的位置,而不是目前的位置,并且由于某种原因它现在已经开始强制关闭

private void initilizeMap() {
    if (googleMap == null) {

        FragmentManager fragmentManager = getSupportFragmentManager();
        SupportMapFragment mapFragment =  (SupportMapFragment)
            fragmentManager.findFragmentById(R.id.iqamah_map);
        googleMap = mapFragment.getMap();           

        googleMap.getUiSettings().setCompassEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(false);
        googleMap.setMyLocationEnabled(true); // false to disable



        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);


        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();


        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);


        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

//            CameraPosition cameraPosition = new CameraPosition.Builder().target(
//                    new LatLng(17.385044, 78.486671)).zoom(12).build();

//            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        url = "https://codingsquared-prod.apigee.net/masaajid?lat="+Double.toString(latitude)+"&long="+Double.toString(longitude);

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        TextView txtview = (TextView) findViewById(R.id.iqamah_listview_text);
        txtview.setText("latitude="+Double.toString(latitude)+" longitude="+Double.toString(longitude));

        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));


    }

}

logcat:

06-28 01:05:01.554: E/AndroidRuntime(13477): FATAL EXCEPTION: main
06-28 01:05:01.554: E/AndroidRuntime(13477): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sahaab.android.muslimzone.test/com.sahaab.muslimzone.activity.IqamahActivity}: java.lang.NullPointerException
06-28 01:05:01.554: E/AndroidRuntime(13477):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2266)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at android.app.ActivityThread.access$600(ActivityThread.java:150)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1298)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at android.os.Looper.loop(Looper.java:213)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at android.app.ActivityThread.main(ActivityThread.java:5225)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at java.lang.reflect.Method.invokeNative(Native Method)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at java.lang.reflect.Method.invoke(Method.java:525)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at dalvik.system.NativeStart.main(Native Method)
06-28 01:05:01.554: E/AndroidRuntime(13477): Caused by: java.lang.NullPointerException
06-28 01:05:01.554: E/AndroidRuntime(13477):    at com.sahaab.muslimzone.activity.IqamahActivity.initilizeMap(IqamahActivity.java:155)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at com.sahaab.muslimzone.activity.IqamahActivity.onCreate(IqamahActivity.java:103)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at android.app.Activity.performCreate(Activity.java:5133)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-28 01:05:01.554: E/AndroidRuntime(13477):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2230)
06-28 01:05:01.554: E/AndroidRuntime(13477):    ... 12 more

还尝试了当前位置:

        Location myLocation = googleMap.getMyLocation();
        LatLng myLatLng = new LatLng(myLocation.getLatitude(),
                myLocation.getLongitude());

        CameraPosition myPosition = new CameraPosition.Builder()
                .target(myLatLng).zoom(17).bearing(90).tilt(30).build();
        googleMap.animateCamera(
            CameraUpdateFactory.newCameraPosition(myPosition));

2 个答案:

答案 0 :(得分:1)

试试这个,它是我用来获取用户当前位置的: - (它检查GPS或NetworkProvider是否可用)

public LatLng getCurrentLocation(Context context)
{
    try
    {
        LocationManager locMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String locProvider = locMgr.getBestProvider(criteria, false);
        Location location = locMgr.getLastKnownLocation(locProvider);

        // getting GPS status
        boolean isGPSEnabled = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // getting network status
        boolean isNWEnabled = locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNWEnabled)
        {
            // no network provider is enabled
            return null;
        }
        else
        {
            // First get location from Network Provider
            if (isNWEnabled)
                if (locMgr != null)
                    location = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled)
                if (location == null)
                    if (locMgr != null)
                        location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }

        return new LatLng(location.getLatitude(), location.getLongitude());
    }
    catch (NullPointerException ne)
    {
        Log.e("Current Location", "Current Lat Lng is Null");
        return new LatLng(0, 0);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return new LatLng(0, 0);
    }
}

答案 1 :(得分:0)

从代码中删除以下代码

  // Getting LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);


    // Creating a criteria object to retrieve provider
    Criteria criteria = new Criteria();


    // Getting the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);


    // Getting Current Location
    Location location = locationManager.getLastKnownLocation(provider);

添加此代码

LocationManager locationManager;
boolean hasNetwrokProvider;

    if (locationManager == null) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    hasNetwrokProvider = locationManager
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (!hasNetwrokProvider) {
                   // Alert for no gps available.
               //ConstantsMethod.buildAlertMessageNoGps(HomeActivity.this);
        return;

    }
    locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER, 0, 100,
            locationListenerNetwork);
    location = locationManager
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);  

实施LocationLienter并在活动

中添加以下代码
public LocationListener locationListenerNetwork = new LocationListener() {
    public void onLocationChanged(Location location) {
        // locationResult.gotLocation(location);
        locationManager.removeUpdates(this);
        locationManager.removeUpdates(locationListenerGps);

    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

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

};