美好的一天。我不确定我的地图应用程序有什么问题,但是当我运行它时它会一直崩溃。消息是“不幸的”,应用程序名称“已经停止。我不确定它是我的片段还是我如何加载地图。这是我的代码:
MainActivity类:
package com.apress.gerber.wbcgapplication;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(checkPlayServices())
{
Intent intent = new
Intent(MainActivity.this,MapsActivity.class);
startActivity(intent);
}
}
//check for google play services
public boolean checkPlayServices(){
Log.d(TAG, "checkPlayServices: checking google services
version");
int available =
GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable
(MainActivity.this);
if(available == ConnectionResult.SUCCESS)
{
//everything is fine and the user can make map requests
Log.d(TAG, "checkPlayServices:Google Play Services is
Working");
return true;
}
else if
(GoogleApiAvailability.getInstance().isUserResolvableError
(available))
{
//an error occured but we cn resolve it
Log.d(TAG, "checkPlayServices: Error Occured but Can Be
Fixed");
Dialog dialog =
GoogleApiAvailability.getInstance().getErrorDialog
(MainActivity.this,available,ERROR_DIALOG_REQUEST);
dialog.show();
}
else
{
Toast.makeText(this, "We cannot connect, please check google
play services version", Toast.LENGTH_SHORT).show();
}
return false;
}
}
MapsActivityClass:
package com.apress.gerber.wbcgapplication;
import android.Manifest;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
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;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback {
private static final String TAG = "MapsActivity";
private static final String FINE_LOCATION =
Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION =
Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private Boolean mLocationPermissionGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private static final float DEFAULT_ZOOM = 15f;
@Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "MAP IS READY", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: MAP IS READY");
mMap = googleMap;
if (mLocationPermissionGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getLocationPermission();
}
//initialize the map
private void initMap(){
Log.d(TAG,"initMap: INITIALIZING MAP");
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
//Getting device location
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: GETTING THE DEVICE LOCATION");
mFusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this);
try
{
if(mLocationPermissionGranted)
{
final Task location =
mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful())
{
Log.d(TAG, "onComplete: FOUND LOCATION");
Location currentLocation = (Location)
task.getResult();
moveCamera(new
LatLng(currentLocation.getLatitude(),
currentLocation.getLongitude()),
DEFAULT_ZOOM);
}
else
{
Log.d(TAG, "onComplete: NO LOCATION FOUND");
Toast.makeText(MapsActivity.this, "UNABLE TO
GET CURRENT LOCATION",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
catch (SecurityException e)
{
Log.e(TAG, "getDeviceLocation: SecurityException " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom){
Log.e(TAG, "moveCamera: MOVING CAMERA TO: LATITUDE: " + latLng.latitude + ", LONGITUDE: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void getLocationPermission(){
Log.d(TAG,"getLocationPermission: GETTING LOCATION PERMISSION");
String [] persmissons = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
mLocationPermissionGranted = true;
initMap();
}
else
{
ActivityCompat.requestPermissions(this,persmissons,LOCATION_PERMISSION_REQUEST_CODE);
}
}
else
{
ActivityCompat.requestPermissions(this,persmissons,LOCATION_PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: CALLED");
mLocationPermissionGranted = false;
switch (requestCode)
{
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0 )
{
for(int i = 0; i < grantResults.length; i++)
{
if(grantResults[i] == PackageManager.PERMISSION_GRANTED)
{
mLocationPermissionGranted = false;
Log.d(TAG, "onRequestPermissionsResult: PERMISSION FAILED");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: PERMISSION GRANTED");
mLocationPermissionGranted = true;
//initialise the map
initMap();
}
}
}
}
}
activity_map.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</android.support.constraint.ConstraintLayout>
<!--<android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>!-->
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.apress.gerber.wbcgapplication.MainActivity">
</android.support.constraint.ConstraintLayout>
这是错误
03-29 13:02:33.702 3053-3053/com.apress.gerber.wbcgapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.apress.gerber.wbcgapplication, PID: 3053
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.apress.gerber.wbcgapplication.MapsActivity$1.onComplete(MapsActivity.java:105)
at com.google.android.gms.tasks.zzf.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5624)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
答案 0 :(得分:0)
我认为您的currentLocation没有得到更新。它在这里是空的。
位置currentLocation =(位置) task.getResult();
因此,你得到的是NullPointerException,因为你试图在这里得到lat和long。
moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()), DEFAULT_ZOOM);
确保获取此变量中的当前位置。然后它会 工作得很好。