Managed to get the codes error free, however upon launching, I somehow always get a null pointer exception at the line mMap = mapFrag.getMap();
Why is this so? Am I missing some imports or some steps? I am unsure if it's the SupportMapFragment or GoogleMap object that's causing the problem.
package com.fragments;
import android.os.Bundle;
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.SupportMapFragment;
public class MapFragment extends SherlockMapFragment {
private GoogleMap mMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = super.onCreateView(inflater, container, savedInstanceState);
SupportMapFragment mapFrag= (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_map);
mMap = mapFrag.getMap(); //null pointer is here
return root;
}
}
Edit: This is part of the implementation based on the solution given in this question here
There is no need of implementing an extra class such as SherlockMapFragment. You can handle the SupportMapFragment inside of the Fragment or the SherlockFragment class code. Look at this.
Note that you do not need to use a custom
Fragment
subclass necessarily to use Maps V2. If your fragment is just purely a map, you can create theMapFragment
orSupportMapFragment
from the activity and configure it there.You do not even need to create some sort of
SherlockMapFragment
to be able to have a map be part of an ActionBarSherlock-based app. The regularSupportMapFragment
works just fine.If you do want to have more business smarts in your fragment, and if you are using ActionBarSherlock, and the business logic in question needs to do things related to ActionBarSherlock (e.g., contribute action items to the action bar), then and only then do you need to worry about having some sort of
SherlockMapFragment
.I can confirm that this gist contains a working
SherlockMapFragment
. Note that it goes into thecom.actionbarsherlock.app
package, as it needs some package-protected access to the rest of ActionBarSherlock.You can then subclass that, such as creating a
MyMapFragment
:You have to be a bit careful on the timing of calling
getMap()
-- too soon and it will returnnull
.onActivityCreated()
seems like a fairly safe time, though you are free to experiment.Then, you just use
MyMapFragment
wherever you would have usedSupportMapFragment
:Here is the complete project containing the above code.