Val
Val

Reputation: 4366

how to serialize/deserialize arrayList(Object)

I have an ArrayList<ItemList>

where ItemList is:

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

    public ItemList() {
    }
}

and Item is:

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

    public Item() {
    }
}

I try to serialize this list:

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 think it's work, becouse I find this file in folder.

But I can't deserialize from file to ArrayList<ItemList>

code:

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

How I can deserialize this ArrayList<ItemList>? I always catch IOException.

Upvotes: 14

Views: 23550

Answers (3)

Abdul
Abdul

Reputation: 1

if you have made subclass then add serializabe method to parent class it will remove the error.

Upvotes: 0

Pshemo
Pshemo

Reputation: 124215

Your Item and ItemList classes needs to implements Serializable

Upvotes: 13

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

I am assuming you have serialized the ItemList not the Item.....

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

   }

Upvotes: -1

Related Questions