-1

I'm trying to write a class which is to handle the maps methods (showmap, addmarker, etc) and I call these methods in an Activity or Fragment, but I get this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

I know what it means, but I canit solve it.
So I hope somebody can help me.

Here is the map calss:

public class MapHandle extends AppCompatActivity implements LocationListener {

private SupportMapFragment mapFragment;
private GoogleMap map;


public void initMap() {


    mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
    if (mapFragment != null) {
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap map) {
                createMap(map);
            }
        });
    } else {
        Toast.makeText(this, "Error - Map Fragment was null!!", Toast.LENGTH_SHORT).show();
    }


}

public void createMap(GoogleMap googleMap) {
    map = googleMap;
    if (map != null) {
        // Map is ready
        Toast.makeText(this, "Map Fragment was loaded properly!", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "Error - Map was null!!", Toast.LENGTH_SHORT).show();
    }
}
}

And here I call it in an Activity:

public class FragOne extends Fragment {

MapHandle mh;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mh = new MapHandle();
    mh.initMap();
    return inflater.inflate(R.layout.frag1,container,false);
}
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Bbeni
  • 75
  • 8

1 Answers1

0

You can't use this

mh = new MapHandle();

The Context becomes null since this is now an un-managed Activity.

You can use onAttach(Context context) and cast the context to get a reference to the parent Activity.

Alternatively, FragOne does not seem to serve any purpose than loading a Map, so have FragOne load and display the map itself (e.g. extends SupportMapFragment)

And, as commented below, MapHandle seems to not need to be an Activity. Primarily because you have not implemented onCreate, which is where you would otherwise be calling initMap

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Also there is no point in `MapHandle` extending `AppCompatActivity` as its is only being used to create Abstraction for `Map` and `Location`. Instead of extending to `AppCompatActivity` Bbeni should pass the required objects for ex. `Context`, `FragmentManager` – Kalpesh Patel Oct 04 '16 at 17:29