从其他活动返回时会重新创建地图片段

时间:2018-08-01 18:15:27

标签: java android google-maps android-studio android-fragments

我正在尝试构建一个使用地图的应用,在该地图上我将一些标记固定到保存其坐标的范围内。当我单击标记时,我正在保存有关那些坐标的一些详细信息,然后返回到地图以添加其他坐标。问题是,当我返回时,地图会重新创建删除已保存的标记。我已经尝试了许多与该主题相关的解决方案,但是当我按下返回按钮时,应用程序崩溃了。您能为我提供一种保存标记和片段状态的解决方案吗?

编辑:即使使用其他解决方案来保存我尝试过的状态,应用程序也崩溃了,绝对不是第32行茶道。

MapsActivity:

 @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;
    mMap.setOnMarkerDragListener(this);
    mMap.setOnMapLongClickListener(this);


    if (mLocationPermissionsGranted) {
        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_maps);
    getLocationPermission();
    initMap();
    if(savedInstanceState != null) {
        CameraPosition savedCameraPosition = savedInstanceState.getParcelable("camera");
        if (savedCameraPosition != null) {
            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(savedCameraPosition));
        }
    }
}

private void getDeviceLocation() {
    Log.d(TAG, "getDeviceLocation: getting the devices current location");

    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    try {
        if (mLocationPermissionsGranted) {

            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: current location is null");
                        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.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));



}

public void onMapLongClick(LatLng latLng) {

    mMap.clear();
    MarkerOptions markerOptions = new MarkerOptions().position(latLng).title(latLng.toString());
    markerOptions.draggable(true);
    mMap.addMarker(markerOptions);
    mMap.setOnMarkerClickListener(this);

    latlngNew = latLng;

    LatLng latlngNew;


}


private void initMap() {
    Log.d(TAG, "initMap: initializing map");
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    mapFragment.getMapAsync(MapsActivity.this);



}
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (mMap != null) {
        outState.putParcelable("camera", mMap.getCameraPosition());
    }
}
private void getLocationPermission() {
    Log.d(TAG, "getLocationPermission: getting location permissions");
    String[] permissions = {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(),
                COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mLocationPermissionsGranted = true;
            initMap();
        } else {
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    } else {
        ActivityCompat.requestPermissions(this,
                permissions,
                LOCATION_PERMISSION_REQUEST_CODE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Log.d(TAG, "onRequestPermissionsResult: called.");
    mLocationPermissionsGranted = 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) {
                        mLocationPermissionsGranted = false;
                        Log.d(TAG, "onRequestPermissionsResult: permission failed");
                        return;
                    }
                }
                Log.d(TAG, "onRequestPermissionsResult: permission granted");
                mLocationPermissionsGranted = true;
                //initialize our map
                initMap();
            }
        }
    }
}

public void changetype(View view) {
    if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) {
        mMap.setMapType(MAP_TYPE_SATELLITE);
    } else
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);


}

@Override
public void onMarkerDragStart(Marker marker) {
    marker.setTitle(marker.getPosition().toString());
    marker.showInfoWindow();
    marker.setAlpha(0.5f);
}

@Override
public void onMarkerDrag(Marker marker) {
    marker.setTitle(marker.getPosition().toString());
    marker.showInfoWindow();
    marker.setAlpha(0.5f);
}

@Override
public void onMarkerDragEnd(Marker marker) {
    marker.setTitle(marker.getPosition().toString());
    marker.showInfoWindow();
    marker.setAlpha(1.0f);

}

@Override
public boolean onMarkerClick(Marker marker) {

    openDialog();
    return false;
}

public void openDialog() {
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialog);
    dialog.setTitle(R.string.default_info_title);
    dialog.show();
    Button bt_da = (Button)dialog.findViewById(R.id.dialog_ok);
    Button bt_nu = (Button)dialog.findViewById(R.id.dialog_cancel);

    bt_da.setOnClickListener(this);
    bt_nu.setOnClickListener(this);
    bt_nu.setOnClickListener(new View.OnClickListener()
                             {
                                 @Override
                                 public void onClick(View v) {
                                     dialog.dismiss();

                                 }
                             }

    );
    bt_da.setOnClickListener(new View.OnClickListener()

                             {
                                 @Override
                                 public void onClick(View v) {
                                     Intent intent=new Intent(MapsActivity.this,MainActivity.class);
                                     intent.putExtra("markerLat", latlngNew.latitude);
                                     intent.putExtra("markerLong", latlngNew.longitude);
                                     startActivity(intent);
                                 }
                             }
    );

}

@Override
public void onClick(View v) {

}

@Override
public void onMapClick(LatLng latLng) {



}

@Override
public void onCameraMove() {

}

以及按Return键时的错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.c.b(com.google.android.gms.maps.a)' on a null object reference
    at com.example.raluca.geoloc.feature.MapsActivity.onCreate(Unknown Source:32)
    at android.app.Activity.performCreate(Activity.java:6975)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2775)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2897) 
    at android.app.ActivityThread.-wrap11(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1598) 
    at android.os.Handler.dispatchMessage(Handler.java:105) 
    at android.os.Looper.loop(Looper.java:251) 
    at android.app.ActivityThread.main(ActivityThread.java:6572) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

第32行具有以下内容:

import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_SATELLITE;

0 个答案:

没有答案