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

眉间皱痕 提交于 2019-11-27 13:39:34

But these FragmentContact is a public class in a *.java-file and has a public empty constructor.

The error is not complaining about FragmentContact. It is complaining about the first inner class of FragmentContact (FragmentContact$1). You cannot have a Fragment implemented as an inner class of anything, as it cannot be instantiated from outside the outer class. A static inner class is fine.

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);
}
  private Entity mEntity;
  public YourFragment() {}
  public static YourFragment getInstance(Entity mEntity) {
    YourFragment fragment = new YourFragment();
    fragment.mEntity = mEntity;
    return fragment;
  }

when you use this fragment,just call the static method getInstance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!