Json for android Markers

Asked

Viewed 80 times

1

I’m trying to loop markers from google maps, picking up information from a json, but I’m stuck on "transferring" the information from doinbackground to the Google method. To better understand, 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 someone shed some light on what is the best way for me to loop the markers using this code?

1 answer

2


This requires a list!

In the AsyncTask, changes the screen only in the method onPostExecute!

Follows 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();
    }

}
  • Hello, thank you so much for your tip, it was very helpful. I used this information in my code, but is still pulling only 1 value (1 Marker), you imagine what can be?

  • How many return in the list?

  • my json returns 4 as examples, and in android’s Marker appears only 1

  • in fact, it is appearing 4, only that one on top of the other, ie with the same value all and same name and description.. rs

  • See the list size (Listadecontroller.size()) ! Put a Log if in ** onPostExecute** 4!

  • got it! I’m going to fix the answer code! It’s because you’re using the same Object Instance mc

  • Place inside the for creating the Jsonobject : Mapascontroller mc = new Mapascontroller();

  • Now it worked out! I think that was it.. rs Vlw same guy, saved me!

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.