我在onDestroyView
中的这一行应用程序中遇到了这个异常:
fm.beginTransaction().remove(mapFragment).commit();
我的代码是:
onCreateView
的{{1}}
Fragment
在SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
googleMap = mapFragment.getMap();
// Retrieve the PlaceAutocompleteFragment.
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.autocomplete_fragment);
// Setting a click event handler for the videosHashMap
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
serviceReqLat = latLng.latitude;
serviceReqLng = latLng.latitude;
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(serviceReqLat, serviceReqLng, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
serviceReqAddress = addresses.get(0).getAddressLine(0);
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
// Register a listener to receive callbacks when a place has been selected or an error has
// occurred.
autocompleteFragment.setOnPlaceSelectedListener(this);
onDestroyView
我试过可能解决方案但仍然遇到这个异常,如何解决这个问题? 提前谢谢。
答案 0 :(得分:0)
通过查看你的代码和Exception,它意味着你无法与视图交互在onSaveInstance被调用之后......所以就像android文档一样,关于onSaveInstanceState可能在onStop()之前调用callBackMethod,其中调用onDestroyView在onStop()之后(根据Android活动/片段生命周期)。可能因为这个你得到错误“无法在onSaveInstanceState之后执行此操作”
另一件事是记住这一点,当你得到错误时... 1)按下后退按钮2)或通过将其放入BackTrak移动到另一个片段
答案 1 :(得分:0)
public abstract int commit()
(...)
事务只能在其包含活动保存其状态之前使用此方法提交。如果在该点之后尝试提交,则将抛出异常。这是因为如果活动需要从其状态恢复,则提交后的状态可能会丢失。有关可能丢失提交的情况,请参阅commitAllowingStateLoss()。
因此,您可以考虑使用commitAllowingStateLoss()
:
fm.beginTransaction().remove(mapFragment).commitAllowingStateLoss();
public abstract int commitAllowingStateLoss()
与commit()类似,但允许在保存活动状态后执行提交。这很危险,因为如果活动需要稍后从其状态恢复,则提交可能会丢失,因此这应仅用于UI状态可以在用户上意外更改的情况。