BadParcelableException in google maps code

前端 未结 6 417
野性不改
野性不改 2020-12-15 22:43

Running slightly modified example of Google Maps throws BadParcelableException in the Google Maps code. The LatLng class is parcelable but it canno

6条回答
  •  不思量自难忘°
    2020-12-15 23:18

    Just to add to the existing answers here, I had been removing my Parcels from the saved state before calling mapView.onCreate and it was working fine.

    However after adding a ViewPager to my Fragment I didn't realise that the BadParcelableException had returned and the code made it to production. It turns out that the ViewPager saves its state too and, because it's part of the Support Library, the Google Map cannot find the class to unparcel it.

    So I opted to invert the process, instead of removing Parcels from the Bundle that I knew about, I opted to create a new Bundle for the map copying over only the map's state.

    private final static String BUNDLE_KEY_MAP_STATE = "mapData";
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Save the map state to it's own bundle
        Bundle mapState = new Bundle();
        mapView.onSaveInstanceState(mapState);
        // Put the map bundle in the main outState
        outState.putBundle(BUNDLE_KEY_MAP_STATE, mapState);
        super.onSaveInstanceState(outState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        mapView = (MapView) view.findViewById(R.id.mapView);
        mapView.getMapAsync(this);
    
        Bundle mapState = null;
        if (savedInstanceState != null) {
            // Load the map state bundle from the main savedInstanceState
            mapState = savedInstanceState.getBundle(BUNDLE_KEY_MAP_STATE);
        }
    
        mapView.onCreate(mapState);
        return view;
    }
    

提交回复
热议问题