Created an application that implements a fragment with Google maps
Code in Main_Activity
private void createMapView() { /** * Catch the null pointer exception that * may be thrown when initialising the map */ try { if (null == googleMap) { googleMap = ((MapFragment) getFragmentManager().findFragmentById( R.id.mapView)).getMap(); /** * If the map is still null after attempted initialisation, * show an error to the user */ if (null == googleMap) { Toast.makeText(getApplicationContext(), "Error creating map", Toast.LENGTH_SHORT).show(); } } } catch (NullPointerException exception){} } XML Code
<fragment android:name="com.google.android.gms.maps.MapFragment" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/mapView" /> When you start the program, everything works, but when I switch to another layout, and then back to layout with a map, the application closes in because of such errors:
java.lang.IllegalStateException: Could not execute method of the activity android.view.InflateException: Binary XML file line #114: Error inflating class fragment java.lang.IllegalArgumentException: Binary XML file line #114: Duplicate id 0x7f0d0082, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.MapFragment In this case, the errors highlighted in blue indicate a line including the layout
setContentView(R.layout.activity_main); Anyone know how to handle?
* Addition: The createMepView () method is called in 2 places: at the very beginning
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvEnabledGPS = (TextView) findViewById(R.id.tvEnabledGPS); tvLocationGPS = (TextView) findViewById(R.id.tvLocationGPS); tvEnabledNet = (TextView) findViewById(R.id.tvEnabledNet); tvLocationNet = (TextView) findViewById(R.id.tvLocationNet); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); createMapView(); addMarker(); } and when returning to this layout
public void bgot (View view){ setContentView(R.layout.activity_main); tvEnabledGPS = (TextView) findViewById(R.id.tvEnabledGPS); tvLocationGPS = (TextView) findViewById(R.id.tvLocationGPS); tvEnabledNet = (TextView) findViewById(R.id.tvEnabledNet); tvLocationNet = (TextView) findViewById(R.id.tvLocationNet); Plt = (TextView) findViewById(R.id.Plt); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); createMapView(); addMarker();
setContentView()is a gross violation of the application architecture and there is no sense in resolving this issue, since the mistake is already in the fact that initially unacceptable practices are used. Do as it should be - one activit (fragment) - one layout and everything will work, otherwise you should deal with such a terrible crutch yourself. This practice has no place at all on SoF.ru - pavlofff