Json for Markers android

1

I'm trying to loop markers from google maps, grabbing information from a json, but I'm stopped at "downloading" information from doinbackground to google's google method. To understand better, follow my code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private ProgressDialog pDialog;
Conexao cx ;

private static String url = "json.php";

private static final String TAG_ID = "evento_id";
private static final String TAG_TITULO = "titulo";
private static final String TAG_DESCRICAO = "descricao";
private static final String TAG_LONGITUDE = "longitude";
private static final String TAG_LATITUDE = "latitude";


MapasController mc = new MapasController();


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

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


    new MapaGet().execute();


}

private class MapaGet extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(MapsActivity.this);
        pDialog.setMessage("Por favor, aguarde...");
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {

        cx =  new Conexao();
        String jsonStr = cx.get(url);

        Log.d("Resposta: ", "> " + jsonStr);

        if (jsonStr != null) {

            try {

                JSONArray jsonArray = new JSONArray(jsonStr);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObj = jsonArray.getJSONObject(i);


                   mc.setLatitude(jsonObj.getDouble(TAG_LATITUDE));
                   mc.setLongitude(jsonObj.getDouble(TAG_LONGITUDE));

                   mc.setTitulo(jsonObj.getString(TAG_TITULO));
                   mc.setDescricao(jsonObj.getString(TAG_DESCRICAO));
                   mc.setId(jsonObj.getString(TAG_ID));


                }
            } catch (JSONException e) {
                Log.e("tag", "Error processing JSON", e);
            }


        } else {
            Log.e("Get: ", "Não foi possível obter quaisquer dados do url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        if (pDialog.isShowing())
            pDialog.dismiss();
        }

}


@Override
public void onMapReady(GoogleMap googleMap) {


mMap = googleMap;

LatLng local = new LatLng(mc.getLatitude(), mc.getLongitude());
mMap.addMarker(new MarkerOptions()
        .position(local)
        .title(mc.getTitulo())
        .snippet(mc.getDescricao())
        .draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(local));


    mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            Intent in = new Intent(MapsActivity.this,DescricaoMaps.class);
            in.putExtra(TAG_ID, mc.getId());
            in.putExtra(TAG_TITULO, mc.getTitulo());
            in.putExtra(TAG_DESCRICAO, mc.getDescricao());
            startActivity(in);


        }
    });

}

Can anyone give me a light on how best I can do the markers loop using this code?

    
asked by anonymous 22.07.2016 / 01:53

1 answer

2

For this you need to use a list!

No AsyncTask , change the screen only in method onPostExecute !

Here's a suggestion:

@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;
    // se o mapa não está nulo , vamos carregar
    if(mMap != null){
        new MapaGet().execute();
    }
}


private class MapaGet extends AsyncTask<Void, Void, Void> {

    // Lista onde vamos guardar os valores 
    List<MapasController> ListaDeController = new ArayList<MapasController>(0);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MapsActivity.this);
        pDialog.setMessage("Por favor, aguarde...");
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {

        cx = new Conexao();
        String jsonStr = cx.get(url);

        Log.d("Resposta: ", "> " + jsonStr);

        if (jsonStr != null) {

            try {

                JSONArray jsonArray = new JSONArray(jsonStr);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObj = jsonArray.getJSONObject(i);

              // Criamos um novo Elemento! Para não sobreescrever o anterior!
               MapasController mc = new MapasController();

                    mc.setLatitude(jsonObj.getDouble(TAG_LATITUDE));
                    mc.setLongitude(jsonObj.getDouble(TAG_LONGITUDE));

                    mc.setTitulo(jsonObj.getString(TAG_TITULO));
                    mc.setDescricao(jsonObj.getString(TAG_DESCRICAO));
                    mc.setId(jsonObj.getString(TAG_ID));

                    // Adicionamos na lista
                    ListaDeController.add(mc);

                }
            } catch (JSONException e) {
                Log.e("tag", "Error processing JSON", e);
            }


        } else {
            Log.e("Get: ", "Não foi possível obter quaisquer dados do url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);


        // Se o tamanho da lista fo maior que zero! 
        if(ListaDeController.size() > 0){
            for(MapasController mc  : ListaDeController){

                LatLng local = new LatLng(mc.getLatitude(), mc.getLongitude());
                mMap.addMarker(new MarkerOptions()
                        .position(local)
                        .title(mc.getTitulo())
                        .snippet(mc.getDescricao())
                        .draggable(true));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(local));


                mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
                    @Override
                    public void onInfoWindowClick(Marker marker) {
                        Intent in = new Intent(MapsActivity.this, DescricaoMaps.class);
                        in.putExtra(TAG_ID, mc.getId());
                        in.putExtra(TAG_TITULO, mc.getTitulo());
                        in.putExtra(TAG_DESCRICAO, mc.getDescricao());
                        MapsActivity.this.startActivity(in);

                    }
                });

            }
        }
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

}
    
22.07.2016 / 13:10