Obtener valor (String) de ArrayList <ArrayList <String >> (); En Java
Sé que es cuestión simple, pero en
ArrayList<ArrayList<String>> collection; ArrayList<String> listOfSomething; collection= new ArrayList<ArrayList<String>>(); listOfSomething = new ArrayList<String>(); listOfSomething.Add("first"); listOfSomething.Add("second"); collection.Add(listOfSomething); listOfSomething.Clear(); listOfSomething.Add("first"); collection.Add(listOfSomething);
Quiero tomar String de ArrayList de ArrayList, y no sé cómo hacerlo. Por ejemplo voy
- Desarrollo / implementación de Linux para Samsung Galaxy S3
- ¿Cómo establecer el valor predeterminado en 0 en edittext cuando no se ingresa nada?
- Excepción "Caracteres ilegales en la consulta en el índice -" en Android
- Cómo crear cuadro de diálogo de alerta Sí / NO en fragmento en Android
- Android dibujar círculo con 2 colores (gráfico circular)
ArrayList<String> myList = collection.get(0); String s = myList.get(0);
¡y funciona! pero:
Gran actualización:
private List<S> valuesS; private List<Z> valuesZ; ArrayList<ArrayList<String>> listOfS; ArrayList<String> listOfZ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Zdatasource = new ZDataSource(this); Zdatasource.open(); valuesZ = Zdatasource.getAllZ(); Sdatasource = new SDataSource(this); Sdatasource.open(); valuesS = Sdatasource.getAllS(); List<Map<String, String>> groupData = new ArrayList<Map<String, String>>(); List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>(); listOfS = new ArrayList<ArrayList<String>>(); listOfZ = new ArrayList<String>(); for (S i : valuesS) { // S is class for (Z j : valuesZ) { // Z is class if(j.getNumerS().equals(i.getNumerS())) { listOfZ.add(j.getNumerZ()); } else { //listOfZ.add("nothing"); } } listOfS.add(listOfZ); if(!listOf.isEmpty()) listOfZ.clear(); } @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { try { ArrayList<String> myList = listOfS.get(groupPosition); String s = myList.get(childPosition); PrintToast("group "+Integer.toString(groupPosition)+", child "+Integer.toString(childPosition) + " , "+ s); } catch(Exception e) { Log.e("FS", e.toString()); } return true; }
Return me java.lang.IndexOutOfBoundsException: El índice no válido 1, el tamaño es 0 cuando hago clic en el elemento que realmente debería existir. No mostrar el código que generan ListView, pero puedo decirte que mi lista contiene 3 elementos: primero es Null listOfZ, la segunda listaOfZ tiene 2 elementos, la tercera listaOfZ tiene 1 elemento.
- ¿Qué significa (savedInstanceState)
- Android: la gravedad falla en API 18+
- Android Studio no puede resolver el símbolo pero el código se ejecuta correctamente
- ¿Leer Byte Array desde la vista de la superficie?
- ¿Cómo mantener la conexión HttpClient Keep-Alive?
- Antecedentes Proceso para escanear la ubicación del usuario a intervalos regulares y actualizar la base de datos local incluso cuando la aplicación no está abierta
- NullPointerExceptions sólo en algunos dispositivos Samsung Galaxy?
- La actividad no está asignada a Android.app.Activity Manifest XML
listOfSomething.Clear(); listOfSomething.Add("first"); collection.Add(listOfSomething);
Usted está borrando la lista aquí y añadiendo un elemento ("primero"), la primera referencia de listOfSomething
se actualiza, así sonce tanto referencia el mismo objeto, por lo que cuando se accede al segundo elemento myList.get(1)
(que no existe Más) obtendrá el nulo.
Observe ambos collection.Add(listOfSomething);
Salvo dos referencias al mismo objeto arraylist.
Debe crear dos instancias diferentes para dos elementos:
ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>(); ArrayList<String> listOfSomething1 = new ArrayList<String>(); listOfSomething1.Add("first"); listOfSomething1.Add("second"); ArrayList<String> listOfSomething2 = new ArrayList<String>(); listOfSomething2.Add("first"); collection.Add(listOfSomething1); collection.Add(listOfSomething2);
Porque el segundo elemento es nulo después de borrar la lista.
Utilizar:
String s = myList.get(0);
Y recuerde, el índice 0 es el primer elemento .
La forma correcta de iterar en una lista dentro de la lista es:
//iterate on the general list for(int i = 0 ; i < collection.size() ; i++) { ArrayList<String> currentList = collection.get(i); //now iterate on the current list for (int j = 0; j < currentList.size(); j++) { String s = currentList.get(1); } }
Una forma más limpia de iterar las listas es:
// initialise the collection collection = new ArrayList<ArrayList<String>>(); // iterate for (ArrayList<String> innerList : collection) { for (String string : innerList) { // do stuff with string } }