Reputation: 6839
I have a java class that extends fragment and inflates an xml layout. Below is my code for that java class:
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
/**
* Created by Mike on 3/17/14.
*/
public class BreweryMap extends Fragment {
public BreweryMap(){}
String beerId = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_brewmap, container, false);
setHasOptionsMenu(true);
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//call async to get breweries to add to
GoogleMap mMap;
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
//add url
String url = "hmyURL";
//send mMap over with async task
new GetVisitedBreweries(getActivity(), mMap).execute(url);
return rootView;
}
}
Here is the xml layout that is being inflated:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
My null pointer error is coming from this line:
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
After looking at my code this makes sense to me that it is NULL because the fragment ID that it is looking for is in my rootView which is stored on this line:
View rootView = inflater.inflate(R.layout.activity_brewmap, container, false);
How can I successfully access the map fragment from my rootView?
I have tried:
mMap = ((SupportMapFragment) rootView.getFragmentManager().findFragmentById(R.id.map)).getMap();
and other combinations. I feel like I am close but not quite.
Upvotes: 1
Views: 865
Reputation: 1233
You are mixing Fragment and SupportFragment. Use SupportFragment everywhere:
In your layout: use com.google.android.gms.maps.SupportMapFragment
In onCreate(): use getSupportFragmentManager()
Upvotes: 1