Attribute that varies with iterations

0

I have this piece of code:

private List<String> cachedRouteMarkers = new ArrayList<>();
private List<Route> cachedRoutes = new ArrayList<Route>();

public List<Route> getRoutes(DataBaseHelper db) {//Saca la lista de marcardores
    Cursor nombreruta = db.nombreruta();
    for (nombreruta.moveToFirst(); !nombreruta.isAfterLast(); nombreruta.moveToNext()) {//Va recorriendo la base de datos por el nombre de ruta

        Cursor wp = db.waypoints(nombreruta.getString(0));//Extrae los waypoints
        for (wp.moveToFirst(); !wp.isAfterLast(); wp.moveToNext()) {
            cachedRouteMarkers.add(wp.getString(0));//Va añadiendo los waypoints
        }
        cachedRoutes.add(new Route(nombreruta.getString(0),cachedRouteMarkers,Color.RED));//Va añadiendo las rutas
        cachedRouteMarkers.clear();
    }
    return cachedRoutes;
}

The getRoutes(DatabaseHelper db) method extracts strings from a database and puts them in cachedRouteMarkers . Then I'm creating an object of type Route , using the above as an attribute and I'll store it in cachedRoutes . I want the number of Strings of cachedRouteMarkers in each Route to remain fixed, but with each iteration it is modified.

How can I make it stay fixed and not change?

Thank you very much in advance:)

    
asked by MDolores 28.08.2018 в 21:37
source

1 answer

0

The explanation you give is not the best in the world, but I gather that what happens to you is that you end up with all Route s with the same "markers".

What happens is that you are passing the same instance cachedRouteMarkers to each instance of Route . clear() cleans the internal state of the instance you have, but you are still working with the same instance.

What you have to do is create a new instance of CachedRouteMarker in each iteration, so that you do not mix the data of Route different%.

Like this

for (nombreruta.moveToFirst(); !nombreruta.isAfterLast(); nombreruta.moveToNext()) {//Va recorriendo la base de datos por el nombre de ruta
    List<String> cachedRouteMarkers = new ArrayList<>(); // Un ArrayList nuevo para cada iteración/Route
                          // No parece que tenga sentido hacer de
                          // esta variable una variable de instancia, sino que debería ser local.
                          // Considera eliminar la definición de la variable de instancia.
    Cursor wp = db.waypoints(nombreruta.getString(0));//Extrae los waypoints
    for (wp.moveToFirst(); !wp.isAfterLast(); wp.moveToNext()) {
        cachedRouteMarkers.add(wp.getString(0));//Va añadiendo los waypoints
    }
    cachedRoutes.add(new Route(nombreruta.getString(0),cachedRouteMarkers,Color.RED));//Va añadiendo las rutas
}
    
answered by 28.08.2018 в 22:03