首页 > 解决方案 > 我在我的 Android 应用程序中的 Google 地图上显示用户的当前位置时遇到问题。谁能告诉我我需要用我的代码做什么

问题描述

这是我的 MapActivity 的代码。它仅用于跟踪用户位置,但仅在移动时才显示位置,但是当我添加代码以在应用程序启动时显示当前位置时,它开始崩溃。

    import android.*;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    LocationManager locationManager;

    LocationListener locationListener;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    {

                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

                    }

                }

            }

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

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

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());

                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));


            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        if (Build.VERSION.SDK_INT < 23) {

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        } else {

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

            } else {

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                mMap.clear();

                mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));


            }


        }


    }
}

问题是,我能够在从模拟器更改和发送位置时获取位置,但是当我添加 else 部分以显示当前位置时,应用程序正在崩溃。

这是应用程序启动时出现的错误。

2019-03-06 01:50:39.000 24094-24094/com.example.userlocationdemo E/AndroidRuntime:致命异常:主进程:com.example.userlocationdemo,PID:24094 java.lang.RuntimeException:无法启动活动 ComponentInfo{ com.example.userlocationdemo/com.example.userlocationdemo.MapsActivity}:java.lang.NullPointerException:尝试在 android.app.ActivityThread 的空对象引用上调用虚拟方法“double android.location.Location.getLatitude()”。 performLaunchActivity(ActivityThread.java:2678) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2743) 在 android.app.ActivityThread.-wrap12(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread. java:1490) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os。Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6165) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$ MethodAndArgsCaller.run(ZygoteInit.java:888) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778) 原因:java.lang.NullPointerException:尝试调用虚拟方法'double android.location.Location .getLatitude()' 在 com.example.userlocationdemo.MapsActivity.onCreate(MapsActivity.java:94) 在 android.app.Activity.performCreate(Activity.java:6687) 在 android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1140) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2631)ActivityThread.main(ActivityThread.java:6165) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 在 com.android。 internal.os.ZygoteInit.main(ZygoteInit.java:778) 原因:java.lang.NullPointerException:尝试在 com.example 的空对象引用上调用虚拟方法“double android.location.Location.getLatitude()”。 userlocationdemo.MapsActivity.onCreate(MapsActivity.java:94) at android.app.Activity.performCreate(Activity.java:6687) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2631)ActivityThread.main(ActivityThread.java:6165) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 在 com.android。 internal.os.ZygoteInit.main(ZygoteInit.java:778) 原因:java.lang.NullPointerException:尝试在 com.example 的空对象引用上调用虚拟方法“double android.location.Location.getLatitude()”。 userlocationdemo.MapsActivity.onCreate(MapsActivity.java:94) at android.app.Activity.performCreate(Activity.java:6687) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2631)在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778) 的 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 调用(本机方法) 原因:java。 lang.NullPointerException:尝试在 android.app.Activity 的 com.example.userlocationdemo.MapsActivity.onCreate(MapsActivity.java:94) 的空对象引用上调用虚拟方法“double android.location.Location.getLatitude()”。 performCreate(Activity.java:6687) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2631)在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778) 的 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 调用(本机方法) 原因:java。 lang.NullPointerException:尝试在 android.app.Activity 的 com.example.userlocationdemo.MapsActivity.onCreate(MapsActivity.java:94) 的空对象引用上调用虚拟方法“double android.location.Location.getLatitude()”。 performCreate(Activity.java:6687) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2631)NullPointerException:尝试在 com.example.userlocationdemo.MapsActivity.onCreate(MapsActivity.java:94) 在 android.app.Activity.performCreate( Activity.java:6687) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2631)NullPointerException:尝试在 com.example.userlocationdemo.MapsActivity.onCreate(MapsActivity.java:94) 在 android.app.Activity.performCreate( Activity.java:6687) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2631)ActivityThread.performLaunchActivity(ActivityThread.java:2631)ActivityThread.performLaunchActivity(ActivityThread.java:2631)

标签: android

解决方案


您正在尝试从第 94 行 MapsActivity 的 oncreate 方法中的 null 位置对象获取纬度,如日志打印中所述

android.location.Location.getLatitude()' 在 com.example.userlocationdemo.MapsActivity.onCreate(MapsActivity.java:94) 的空对象引用上


推荐阅读