Why do I get a null pointer exception when I do GoogleMap map = ((SupportMapFragment) manager.findFragmentById(R.id.map)).getMap()? I must be missing something very obvious:
public class ReviewMap extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review_map);
if (savedInstanceState == null) {
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().add(R.id.container, new MapFragment()).commit();
GoogleMap map = ((SupportMapFragment) manager.findFragmentById(R.id.map)).getMap(); // Null pointer exception
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.review_map, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public static class MapFragment extends Fragment {
public MapFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_review_map, container, false);
return rootView;
}
}
}
My layouts:
activity_review_map.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="atorch.shortestpaths.ReviewMap"
tools:ignore="MergeRootFrame" />
fragment_review_map.xml -- this is the one I am trying to access with R.id.map:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
If I comment out the GoogleMap map = ((SupportMapFragment) manager.findFragmentById(R.id.map)).getMap() line in the first block of code, everything works as expected (I see a map under an ActionBar); if I leave the line in, I get a Null pointer exception in my logcat, and the app crashes before any map is displayed.
0 comments:
Post a Comment