Search code examples
javaandroidgoogle-mapsnullpointerexceptionmarkerclusterer

NullPointerException whiling trying to cluster markers google maps


I'm building a map on my app and everything works fine until I add my ClusterItem to my ClusterManager throwing the exception:

Attempt to read from field 'double com.google.android.gms.maps.model.LatLng.longitude' on a null object reference

public class MapaActivity extends FragmentActivity implements OnMapReadyCallback {

BancoDadosController bancoDadosController;

private List<Obra> listaPlot;
private String numObra, numeroObra, tipoObra, descricao;

private double latitude;
private double longitude;
private String geoPonto;
private GoogleMap gMap;
private LatLng pontoFinal;

private ClusterManager<ItemCluster> mClusterManager;
private ItemCluster itemCluster;


private SharedPreferences pegaIdJurisdicionado;
private static final String USER_AUTH = "Autentication";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mapa);

    //getSupportActionBar().setDisplayShowHomeEnabled(true);


    bancoDadosController = new BancoDadosController(this);
    pegaIdJurisdicionado = getSharedPreferences(USER_AUTH,0);
    String idJurisdicionado = pegaIdJurisdicionado.getString("idJurisdicionado", null);
    listaPlot = bancoDadosController.buscarListaMapa("3", "5527");

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapaDespesa);
    mapFragment.getMapAsync(this);
}

private void setUpClusterer(GoogleMap googleMap) {

    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-7.116289, -34.850414), 4.5f));

    mClusterManager = new ClusterManager<ItemCluster>(this, googleMap);
    mClusterManager.setRenderer(new IconePersonalizado(MapaActivity.this, googleMap,mClusterManager));

    final IconePersonalizado iconePersonalizado = new IconePersonalizado(this,gMap,mClusterManager);
    mClusterManager.setRenderer(iconePersonalizado);
    mClusterManager.getMarkerCollection().setOnInfoWindowAdapter(new InfoWindowMapa(LayoutInflater.from(this)));

    gMap.setInfoWindowAdapter(mClusterManager.getMarkerManager());
    googleMap.setOnCameraIdleListener(mClusterManager);
    googleMap.setOnMarkerClickListener(mClusterManager);
    googleMap.setOnInfoWindowClickListener(mClusterManager);

    addItemsCluster();

}

private void addItemsCluster() {

    for (int i = 0; i < listaPlot.size(); i++) {

        geoPonto = listaPlot.get(i).getGeoReferenciamento();
        pontoFinal = tratamentoGeoPonto(geoPonto);


        numObra = listaPlot.get(i).getNumeroObra();
        tipoObra = listaPlot.get(i).getTipoObra();
        descricao = listaPlot.get(i).getDescricaoObra();

        itemCluster = new ItemCluster(pontoFinal, numObra, tipoObra, descricao);
        try{
            mClusterManager.addItem(itemCluster);
        }catch (NullPointerException e){
            Log.d("Andre", String.valueOf(itemCluster.getPosition()));
            e.printStackTrace();
        }

    }

}

private LatLng tratamentoGeoPonto(String valor){
    String geoPontoFormatado = "";

    geoPontoFormatado = valor.substring(1, (valor.length()-1));
    String[] pontos = geoPontoFormatado.split(",");

    double lat = Double.parseDouble(pontos[0]);
    double lngt = Double.parseDouble(pontos[1]);

    LatLng pontoTratado = new LatLng(lat, lngt);

    return pontoTratado;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    gMap = googleMap;
    gMap.getUiSettings().setRotateGesturesEnabled(false);
    gMap.getUiSettings().setZoomControlsEnabled(true);
    setUpClusterer(gMap);

    mClusterManager.setOnClusterItemInfoWindowClickListener(new ClusterManager.OnClusterItemInfoWindowClickListener<ItemCluster>() {
        @Override
        public void onClusterItemInfoWindowClick(ItemCluster itemCluster) {
            numeroObra = itemCluster.getNumeroObra();

            Intent passarObra = new Intent(MapaActivity.this,CardObraActivity.class);
            passarObra.putExtra("obraDigitada",numeroObra);
            startActivity(passarObra);
        }
    });

    mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<ItemCluster>() {
        @Override
        public boolean onClusterItemClick(ItemCluster itemCluster) {

            return false;
        }
    });

    mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener<ItemCluster>() {
        @Override
        public boolean onClusterClick(Cluster<ItemCluster> cluster) {
            float teste = gMap.getCameraPosition().zoom;

            CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(teste+6).build();
            gMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            return false;
        }
    });
}

}

And here is my ClusterItem class:

public class ItemCluster implements ClusterItem{
private LatLng mPosition;
private String numeroObra;
private String descricao;
private String tipoObra;

public ItemCluster(LatLng mPosition, String numeroObra, String descricao, String tipoObra) {
    this.mPosition = mPosition;
    this.numeroObra = numeroObra;
    this.descricao = descricao;
    this.tipoObra = tipoObra;
}

public LatLng getmPosition() {
    return mPosition;
}

public String getNumeroObra() {
    return numeroObra;
}

public String getDescricao() {
    return descricao;
}

public String getTipoObra() {
    return tipoObra;
}

@Override
public LatLng getPosition() {
    return null;
}

@Override
public String getTitle() {
    return null;
}

@Override
public String getSnippet() {
    return null;
}

}

all my variables have values and it's all ok until reach on this function

private void addItemsCluster() {

    for (int i = 0; i < listaPlot.size(); i++) {

        geoPonto = listaPlot.get(i).getGeoReferenciamento();
        pontoFinal = tratamentoGeoPonto(geoPonto);


        numObra = listaPlot.get(i).getNumeroObra();
        tipoObra = listaPlot.get(i).getTipoObra();
        descricao = listaPlot.get(i).getDescricaoObra();

        itemCluster = new ItemCluster(pontoFinal, numObra, tipoObra, descricao);
        try{
            mClusterManager.addItem(itemCluster);
        }catch (NullPointerException e){
            Log.d("Andre", String.valueOf(itemCluster.getPosition()));
            e.printStackTrace();
        }
    }
}

And that's my Select function to return my list to plot the map

public List<Obra> buscarListaMapa(String tipoGeoReferenciamentoFiltro, String idJurisdicionadoFiltro) {
    SQLiteDatabase db = helper.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM " + BancoDadosHelper.TABELA_OBRA + " WHERE "+ BancoDadosHelper.COLUNA_ID_TIPO_GEOREFERENCIAMENTO + " = '"+tipoGeoReferenciamentoFiltro+"' and "+
            BancoDadosHelper.COLUNA_ID_JURISDICIONADO+" = '"+idJurisdicionadoFiltro+"'", null);


    List<Obra> listaMapa = new ArrayList<>();

    if (cursor.moveToFirst()) {
        do {
            String numObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_NUM_OBRA));
            String descObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_DESCRICAO_OBRA));
            String geoReferenciamento = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_GEOREFERENCIAMENTO));
            String tipoObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_TIPO_OBRA));
            Obra novaObra = new Obra(numObra, descObra, tipoObra, geoReferenciamento);
            listaMapa.add(novaObra);

        } while (cursor.moveToNext());
    }

    cursor.close();
    db.close();
    return listaMapa;
}

Solution

  • The problem may be in your ItemCluster.class, In your case getPosition() returns null.

     @Override
        public LatLng getPosition() {
            return new LatLng(getSLatitude(), getSLongitude());
        }