在Google Map中获取NullPointerException

时间:2014-02-28 06:16:24

标签: android google-maps nullpointerexception google-maps-api-2

我正在使用 Google地图V2 。我正在使用 nullpointerexception

我尝试调试我的代码,但我没有得到代码中的问题。

活动代码

public class MainActivity extends FragmentActivity implements LocationListener,
        OnMarkerClickListener 
{    
    private GoogleMap mMap;
    private LocationManager locationManager;
    private String provider;
    Button ib_back, notify;
    Double Latitude, longitude;
    Circle circle;

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

        mMap = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map2)).getMap();
        mMap.setMyLocationEnabled(true);

        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabledGPS = service
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean enabledWiFi = service
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!enabledGPS) {
            Toast.makeText(MainActivity.this, "GPS signal not found",
                    Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        } else if (!enabledWiFi) {
            Toast.makeText(MainActivity.this, "Network signal not found",
                    Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }

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

        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            // Toast.makeText(BasicMapActivity_new.this, "Selected Provider " +
            // provider,
            // Toast.LENGTH_SHORT).show();
            onLocationChanged(location);
        } else {

            // do something
        }
        setUpMap();
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
        setUpMapIfNeeded();
    }

    private void setUpMapIfNeeded() {
        if (mMap == null) {
            mMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map2)).getMap();
            mMap.setMyLocationEnabled(true);

            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        mMap.getUiSettings().setCompassEnabled(true);
        mMap.getUiSettings().setTiltGesturesEnabled(true);
        mMap.getUiSettings().setRotateGesturesEnabled(true);
        mMap.getUiSettings().setScrollGesturesEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setZoomGesturesEnabled(true);
        setLocation();
    }

    public void setLocation() {

        Circle circle = mMap.addCircle(new CircleOptions()
                .center(new LatLng(Latitude, longitude)).radius(100) /// Here i am getting the exception
                .strokeColor(Color.RED));

        float[] distances = new float[1];

        //Array List for list of lat and log. 
        //  final ArrayList<Integer> arrayList = new ArrayList<Integer>();

        for (int i = 0; i < 10; i++) {
            // random latitude and logitude
            double[] randomLocation = createRandLocation(Latitude, longitude);

            // Adding a marker
            MarkerOptions marker = new MarkerOptions().position(
                    new LatLng(randomLocation[0], randomLocation[1])).title(
                    "Hello Maps " + i);

            Location.distanceBetween(randomLocation[0], randomLocation[1],
                    circle.getCenter().latitude, circle.getCenter().longitude,
                    distances);

            // arrayList.add((int) distances[0]);

            Log.e("Random", "> " + randomLocation[0] + ", " + randomLocation[1]);
            Toast.makeText(
                    MainActivity.this,
                    " Random Location " + randomLocation[0] + ","
                            + randomLocation[0], Toast.LENGTH_LONG).show();

            if (i == 0)
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
            if (i == 1)
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
            if (i == 2)
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
            if (i == 3)
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            if (i == 4)
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
            if (i == 5)
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
            if (i == 6)
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_RED));
            if (i == 7)
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
            if (i == 8)
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
            if (i == 9)
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));

            if (distances[0] < circle.getRadius()) {
                // Add Marker belong here
                mMap.addMarker(marker);
            }               
        }    
    }

    @Override
    public boolean onMarkerClick(Marker arg0) {
        // TODO Auto-generated method stub
        return false;
    }

    Marker startPerc = null;
    Location old_one;

    @Override
    public void onLocationChanged(Location location) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        // Toast.makeText(BasicMapActivity_new.this, "Location " + lat+","+lng,
        // Toast.LENGTH_LONG).show();
        LatLng coordinate = new LatLng(lat, lng);
        Latitude = lat;
        longitude = lng;

        Toast.makeText(MainActivity.this,
                "Location " + coordinate.latitude + "," + coordinate.longitude,
                Toast.LENGTH_LONG).show();

        startPerc = mMap.addMarker(new MarkerOptions()
                .position(coordinate)
                .title("Current Location")
                .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 18.0f));
    }

    private double[] createRandLocation(double latitude, double longitude) {
        return new double[] { latitude + ((Math.random() - 0.5) / 500),
                longitude + ((Math.random() - 0.5) / 500),
                150 + ((Math.random() - 0.5) * 10) };
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }           
}

这里我得到空指针异常.center(new LatLng(Latitude, longitude)).radius(100)

以下是我的Log-Cat错误

02-28 11:35:46.204: E/AndroidRuntime(20215): FATAL EXCEPTION: main
02-28 11:35:46.204: E/AndroidRuntime(20215): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.googlemap/com.test.googlemap.MainActivity}: java.lang.NullPointerException
02-28 11:35:46.204: E/AndroidRuntime(20215):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at android.app.ActivityThread.access$600(ActivityThread.java:162)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at android.os.Handler.dispatchMessage(Handler.java:107)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at android.os.Looper.loop(Looper.java:194)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at android.app.ActivityThread.main(ActivityThread.java:5371)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at java.lang.reflect.Method.invokeNative(Native Method)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at java.lang.reflect.Method.invoke(Method.java:525)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at dalvik.system.NativeStart.main(Native Method)
02-28 11:35:46.204: E/AndroidRuntime(20215): Caused by: java.lang.NullPointerException
02-28 11:35:46.204: E/AndroidRuntime(20215):    at com.test.googlemap.MainActivity.setLocation(MainActivity.java:127)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at com.test.googlemap.MainActivity.setUpMap(MainActivity.java:121)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at com.test.googlemap.MainActivity.onCreate(MainActivity.java:83)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at android.app.Activity.performCreate(Activity.java:5122)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
02-28 11:35:46.204: E/AndroidRuntime(20215):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)

2 个答案:

答案 0 :(得分:2)

Latitudelongitude未初始化,因此抛出NullPointerException。在以下代码中使用变量之前初始化变量。

Circle circle = mMap.addCircle(new CircleOptions()
            .center(new LatLng(Latitude, longitude)).radius(100) /// Here i am getting the exception
            .strokeColor(Color.RED));

答案 1 :(得分:0)

而不是

double lat = location.getLatitude();
double lng = location.getLongitude();

double lat = location.getLatitude();
double lng = location.getLongitude();
if(lat == null || lng == null){
   lat=0.0;
   lng=0.0;
}

double lat = location.getLatitude();
double lng = location.getLongitude();
if(lat == 0.0 || lng == 0.0){
   lat=0.0;
   lng=0.0;
}

甚至

double lat = location.getLatitude();
double lng = location.getLongitude();
if(lat == null || lng == null || lat == 0.0 || lng == 0.0){
   lat=0.0;
   lng=0.0;
}