0

I am using the following method to save ArrayLists to serialized objects. File is generating successfully. However when I try to read it I get java.lang.ClassCastException. in line Item item = (Item)ois.readObject(); what is the proper way of loading the file?

save

String storage_path = Environment.getExternalStorageDirectory() + "/notesBackup.memo";
    Log.d("storage path",storage_path);
    File file2 = new File(storage_path);
    ArrayList<Item> items = new ArrayList();
    File filesdir = getFilesDir();
    ArrayList<String> itemsfiles = new ArrayList();
    for (String file : filesdir.list()) {
        if (file.endsWith(FILE_EXTENSION)) {
            itemsfiles.add(file);

        }
    }
    int i = 0;
    while (i < itemsfiles.size())

    {
        try {

            FileInputStream fis = openFileInput((String) itemsfiles.get(i));
            ObjectInputStream ois = new ObjectInputStream(fis);
            items.add((Item) ois.readObject());

            FileOutputStream fos = new FileOutputStream(file2);
            ObjectOutputStream ous = new ObjectOutputStream(fos);
            ous.writeObject(items);
            fis.close();
            ois.close();
           fos.close();
            ous.close();
            Log.d("file is creating",String.valueOf(i));


            i++;


        } catch (IOException e2) {
            e = e2;
        } catch (ClassNotFoundException e3) {
            e = e3;
        }


    }

load

    public static ArrayList<Item> getbackupitems(Context context) {
    Exception e;
    ArrayList<Item> items = new ArrayList();
    File filesdir = new File(Environment.getExternalStorageDirectory()+"/notesBackup.memo");
    if(filesdir.exists()){
        Log.d("file","found");
    }
    else {
        Log.d("file", "not found");
    }

        try {
            FileInputStream fis = new FileInputStream(filesdir);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Item item = (Item)ois.readObject();
            items.add(item);
            fis.close();
            ois.close();
           Log.d(items.toString(),"");
        } catch (IOException e2) {
            e = e2;
        } catch (ClassNotFoundException e3) {
            e = e3;
        }

    return items;

}

1 Answer 1

1

You are reading the list and trying to cast it to Item and that's why the error.

Try the below and check

List<Item> itemList = new  ArrayList<>();
 itemList = (List<Item>) ois.readObject();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.