Fragment - InstantiationException: no empty Constructor -> Google Maps v2?

后端 未结 3 569
时光取名叫无心
时光取名叫无心 2020-12-03 03:13

I get this error message, when I open a closed App again via App-Change button:

Caused by: java.lang.InstantiationEx         


        
3条回答
  •  無奈伤痛
    2020-12-03 03:58

    I've had this issue for ages and finally the comments on here have solved it for me. Nice information about the $1 meaning anonymous inner class.

    Move your map initialisation to a new Public Class, e.g. MyMapFragment.java. This will allow the fragment to be instantiated without the instance of

    For those still not sure how to fix it. Write the code as follows (using the example code from the original question):

    //Existing code to instantiate map
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
        View v = inflater.inflate(R.layout.fragment_contact, null);
    
        try {
            MapsInitializer.initialize(this.getActivity().getApplicationContext());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }
    
        fragment = new MyMapFragment();
    
        //added callback for catching when the map has finished loading
        mapFragment.setLoadedCallback(new MapLoadedCallback() {
            @Override
            public void onLoaded(GoogleMap map) {
                mMap = map;
            }
        });
    
        getFragmentManager().beginTransaction().replace(R.id.fragment_orte_map_parent, fragment).commit();
    
        return v;
    }
    ....
    

    Create new MyMapFragment.java so that it is no longer an inner class. This will allow the fragment to be created without it's outer class.

    public class MyMapFragment extends SupportMapFragment 
    {
        GoogleMap mMap;
        public MyMapFragment() {
        }
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
             mMap = fragment.getMap();
             if (mMap != null) {
                 mCallback.onLoaded(mMap);
            }
        }
    }    
    

    Create MapLoadedCallback.java to allow you to handle when the map has finished loading and to retrieve an instance of the loaded map object

    public interface MapLoadedCallback {
        void onLoaded(GoogleMap map);
    }
    

提交回复
热议问题