Google Maps API 2在Singleton中提供NullPointer

时间:2016-02-03 18:50:38

标签: android nullpointerexception singleton google-maps-android-api-2 google-maps-api-2

我有一个非常简单的实例,用于创建IconGenerator并使其在地图上可见。

问题是,每次想要创建IconGenerator iconita = new IconGenerator(getContext())时,它都会给我一个NullPointerException;

public class Controller {
GoogleMap mMap;
Context context;
private static Controller instance;

private Controller() {
}

public static Controller getInstance() {
    if (instance == null) {
        instance = new Controller();
    }
    return instance;
}

public void setContext() {
    this.context = context;
}

public Context getContext() {
    return context;
}

public Map<String, List<Marker>> adaugaRuta(ShowTheRute theRoute) {
    Map<String, List<Marker>> objectMap = new HashMap<>();

    IconGenerator iconita = new IconGenerator(getContext()); <-- HERE it gives NullPointerException
    iconita.setContentPadding(5, -5, 5, -5);
    iconita.setRotation(-270);
    iconita.setContentRotation(270);

    Bitmap iconbit = iconita.makeIcon("Marker 1.");
    final Marker mae = mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(iconbit)).position(new LatLng(46.762035, 23.597659)).anchor(0f, 0.5f));
    mae.isVisible();

    List<Marker> marker1 = new ArrayList<>();
    marker1.add(mae);

    objectMap.put("marker1", marker1);

    theRoute.getTheRute(objectMap);
    return objectMap;
}

}

1 个答案:

答案 0 :(得分:1)

您的上下文对象永远不会设置,您在上下文的设置器中有错误

public void setContext() {
    this.context = context;
}

你实际上正在用自己重写上下文.. 它应该是:

public void setContext(Context context) {
    this.context = context;
}