Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android mapview with fragments can't be added twice?

I am using the android compatibility class with the hack for using mapviews in a fragment found here: https://github.com/petedoyle/android-support-v4-googlemaps

Unfortunately, what I am finding is that if the mapfragment gets removed from the activity, and then readded, I get the "You are only allowed to have a single MapView in a MapActivity" error."

I understand the principle behind the error, and tried destroying the mapview in the fragments onPause method. Unfortunately I can't seem to destroy the mapview completely, since I am still getting it. My Code looks like this:

private RelativeLayout layout; 
private MapView mp;

public void onResume(){
    super.onResume();
    Bundle args = getArguments();
    if(mp == null)
    {
        mp = new MapView(getActivity(), this.getString(R.string.map_api_key)); 
        mp.setClickable(true);
    }

    String request = args.getString("requestId");
    layout = (RelativeLayout) getView().findViewById(R.id.mapholder);
    layout.addView(mp);
    //TextView txt = (TextView) getView().findViewById(R.id.arguments);
    //txt.setText(request);
}

public void onPause(){
    super.onPause();
    layout.removeView(mp);
    mp = null;
}

Does anyone have any thoughts on what the reference I am neglecting to destroy here?

like image 348
akhalsa Avatar asked Oct 19 '11 08:10

akhalsa


1 Answers

I encountered the same issue. Here is how I solved it :

  • As it should be only one instance of the mapView in the activity, I initialize it in onCreate method in Activity :

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // initialize MapView programmatically to be used in Fragment :
        this.mActivityMapView = new MapView(MainActivity.this, getString(R.string.debug_mapview_apikey));
    
        setContentView(R.layout.activity_main);
    }
    
  • Then I recover it in the fragment onCreateView method :

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.mMapView = ((MainActivity) getActivity()).getMapView();
        return this.mMapView;
    }
    
  • And I destroy it in the fragment onDestroy method :

    public void onDestroy() {
        NoSaveStateFrameLayout parentView = (NoSaveStateFrameLayout) this.mMapView.getParent();
        parentView.removeView(this.mMapView);
        super.onDestroy();
    }
    
like image 58
Max Avatar answered Sep 23 '22 05:09

Max