1

Hola muy buenas estoy haciendo una aplicación en Android, el caso, es que tengo un mapa, y dentro de ese mapa hay uno puntos que se generan pasando una latitud y longitud dentro de una base de datos. Dentro de esos puntos hago que me lleven a otra activity, para ver la información, del punto que yo he clickeado, dicha información la parseo mediante SAX y la guardo. La Cuestión que tengo es que siempre me aparece el ultimo Nombre de los objetos que he parseado.

public class Sitio {
private String Nombre;
private double Latitud;
private double Longitud;
private String Imagen;



public Sitio(String nombre, double longitud, double latitud)
{
    Nombre = nombre;
    Longitud = longitud;

    Latitud = latitud;
}

public String getImagen() {
    return Imagen;
}

public void setImagen(String imagen) {
    Imagen = imagen;
}
public String getNombre() {
    return Nombre;
}

public void setNombre(String nombre) {
    Nombre = nombre;
}

public double getLongitud() {
    return Longitud;
}

public void setLongitud(double longitud) {
    Longitud = longitud;
}

public double getLatitud() {
    return Latitud;
}

public void setLatitud(double latitud) {
    Latitud = latitud;
}

`

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar3);
    toolbar.setTitle(R.string.app_name);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    MainMenu.CargarXmlTask tarea = new MainMenu.CargarXmlTask();
    tarea.execute("http://theturistllion.hol.es/IserccionDeUbicacion.php");


    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION)) {

        } else {

            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS);

        }
    }
}
private class CargarXmlTask extends AsyncTask<String,Integer,Boolean> {

    protected Boolean doInBackground(String... params) {

        ParseoSax saxparser =
                new ParseoSax(params[0]);

        sitio = saxparser.parse();

        return true;
    }

    protected void onPostExecute(Boolean result)
    {
        for(int i=0; i<sitio.size(); i++)
        {
            cali = new LatLng(sitio.get(i).getLatitud(), sitio.get(i).getLongitud());

            marca.addMarker(new MarkerOptions()
                    .position(cali)
                    .title(sitio.get(i).getNombre()));


        }
        marca.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                Intent intent = new Intent(MainMenu.this, Informacion_sites.class);
                startActivity(intent);
            }
        });        }
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {

            }
            return;
        }
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    original = googleMap;
    miUbicacion();

    marca = googleMap;

    original.setMyLocationEnabled(true);
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
}
public void Marcador(double lat, double log)
{
    LatLng cordena = new LatLng(lat, log);
    CameraUpdate ubicacion = CameraUpdateFactory.newLatLngZoom(cordena, 16);
    if (marcador != null) {
        marcador.remove();
    }
    mMap.animateCamera(ubicacion);
}
private void actualizar(Location location) {
    if (location != null) {
        lat = location.getLatitude();
        log = location.getLongitude();
        Marcador(lat, log);
    }
}
LocationListener locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        actualizar(location);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};
private void miUbicacion() {

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    actualizar(location);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 15000,0,locationListener);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_informacion_sites);
    collapsingToolbar =
            (CollapsingToolbarLayout) findViewById(R.id.collapse_toolbar);
    toolbar = (Toolbar) findViewById(R.id.MyToolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    //Botón atrás declarado
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    img = (ImageView) findViewById(R.id.bgheader);
    Informacion_sites.CargarXmlTask tarea = new Informacion_sites.CargarXmlTask();
    tarea.execute("http://theturistllion.hol.es/IserccionDeUbicacion.php");

}
//Acción del Botón volver atrás
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
private class CargarXmlTask extends AsyncTask<String,String,Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

    protected Boolean doInBackground(String... params) {

        ParseoSax saxparser =
                new ParseoSax(params[0]);

        sitio = saxparser.parse();

        return true;
    }

    protected void onPostExecute(Boolean result) {
        for (int i = 0; i < sitio.size(); i++)
        {
            collapsingToolbar.setTitle(sitio.get(i).getNombre());
            toolbar.setTitle(sitio.get(i).getNombre());
        }
        for (int i = 0; i < sitio.size(); i++)
        {
                GetXMLTask task = new GetXMLTask();
                task.execute(new String[]{sitio.get(i).getImagen()});
        }
    }
}

private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... urls) {
        Bitmap map = null;
        for (String url : urls) {
            map = downloadImage(url);
        }
        return map;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        img.setImageBitmap(result);
    }

    private Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.
                    decodeStream(stream, null, bmOptions);
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;
    }

    // Makes HttpURLConnection and returns InputStream
    private InputStream getHttpConnection(String urlString)
            throws IOException {
        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return stream;
    }
}

pongo la clase del mapa donde creo los sitios, la activity información es que que sale cuando clickeo y necesito saber, como poner cuando clickeo una pues que salga la inforacion de esa y no del ultimo objeto.

0

1 respuesta 1

0

El problema se encuentra en tu clase ParseoSax , esta obteniendo solo un elemento en el listado de objetos, por esa razón solo se muestra un elemento.

ParseoSax saxparser = new ParseoSax(params[0]);
sitio = saxparser.parse();

Se muestra el último elemento por que probablemente estas sobre escribiendo el objecto y al final solo entrega los datos del último, debes crear una nueva instancia por cada elemento y agregarla a tu array mediante el método add()

List<Sitio> sitios = new ArrayList<Sitio>();

for(...){
   Sitio sitio new Sitio(); //Crea nueva instancia.
   ...
   ...
    sitios.add(sitio); //Agrega elementos al array.
}

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.