2012-07-09 29 views
14

Tengo una ArrayList<ItemList>cómo serializar/deserializar arrayList (Objeto)

donde ITEMLIST es:

public class ItemList { 
    public ArrayList<Item> it = new ArrayList<Item>(); 
    public String name = ""; 

    public ItemList() { 
    } 
} 

y artículo es:

public class Item { 
    public String name = ""; 
    public int count = 0; 

    public Item() { 
    } 
} 

trato de serializar esta lista:

try { 
      FileOutputStream fileOut = new FileOutputStream(sdDir + serFile); 
      ObjectOutputStream out = new ObjectOutputStream(fileOut); 
      out.writeObject(List_Of_Lists); 
      out.close(); 
      fileOut.close(); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

I thi Es trabajo, porque encuentro este archivo en la carpeta.

Pero no puedo deserializar de archivo a ArrayList<ItemList>

código:

 try { 
      FileInputStream fileIn = new FileInputStream(sdDir + serFile); 
      ObjectInputStream in = new ObjectInputStream(fileIn); 
      List_Of_Lists = (ArrayList<ItemList>) in.readObject(); 
      Log.i("palval", "dir.exists()"); 
      in.close(); 
      fileIn.close(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

Cómo yo deserializar este ArrayList<ItemList>? Siempre capturo IOException.

+0

Por favor, publique toda la excepción stacktrace – Tomer

+0

¿Está serializando el arraylist solo es decir, la variable "it" o la clase ItemList? – prashant

+0

'Siempre capturo IOException'. Sí, pero ¿has leído el mensaje que contiene? Contiene la respuesta. – EJP

Respuesta

13

Sus Item y ItemList clases tiene que implements Serializable

+1

thx, es trabajo ahora. – Val

+0

¿Qué es el artículo implementar parcelable? ¿Se puede implementar serializable al mismo tiempo? –

+0

@the_prole No estoy seguro de lo que quiere decir con "¿Qué es el artículo implementar parcelable?". Acerca de "¿Se puede implementar serializable al mismo tiempo?" Probablemente sí, ya que la clase puede implementar muchas interfaces y "Serializable" realmente no introduce ningún método nuevo, por lo que no debería haber ningún conflicto. – Pshemo

-1

Estoy asumiendo que ha serializado el ITEMLIST no el artículo .....

ArrayList<ItemList> arr = (ArrayList<ItemList>) in.readObject(); 

for (ItemList a : arr) 
    { 
     // In this loop by iterating arr, you will get the whole List of ItemList 

    } 
+0

w8. Lo intentaré ... – Val

+0

ok ... házmelo saber ... en realidad no tienes tu código completo, por lo que es difícil de adivinar –

+0

Artículo, ItemList necesita implementar Serializable. – Val

0

si ha hecho subclase a continuación, añadir el método serializabe a los padres clase eliminará el error.

+0

¿Tiene un ejemplo de código? – mhatch