Search code examples
javaandroidarraylistandroid-external-storage

How to save arrayList<Custom Object> in local storage android?


I have an app that fetches uri and name of the images and returns arrayList of ArrayList<ImageModel>. Where Image Model consists uri and name two variables and Getter and Setter for each.

try {
            FileOutputStream outputStreamWriter = getContext().openFileOutput("config.txt", Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(outputStreamWriter);
            oos.writeObject(arrayList);
            oos.close();
            outputStreamWriter.close();
        } catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        }

When I try to save arrayList Using above methid it throws java.io.NotSerializableException: android.net.Uri$HierarchicalUri Exception. But, my ImageModel implementsSerializable.

 try {
            FileInputStream fis = getContext().openFileInput("config.txt");
            ObjectInputStream ois = new ObjectInputStream(fis);
            Object object = ois.readObject();
            return object;
        } catch (Exception ex) {
            return null;
        }

Because File is not written it makes this read method return null. So, I need suitable solution to save that arrayList to local storage and retrive it. Further I am going to load images uri by arrayList.get() method. So, I suppose ArrayList is must.


Solution

  • You cannot save objects to storage directly, you have to serialize them and then store this serialized data into storage. You have to read the serialized data, then deserialize it to get back your object. More on serialization

    In your code, oos.writeObject() requires that passed object must be serializable, but your ImageModel is not because of having a member of type Uri.

    Possible workaround: Modify your ImageModel class to be serializable. And keep your storage read/write logic unchanged.

    ImageModel class

    public class ImageModel implements Serializable {
        private String uriString;
        private String name;
    
        public ImageModel(Uri uri, String name) {
            this.uriString = uri.toString();
            this.name = name;
        }
        
        public Uri getUri() {
            return Uri.parse(uriString);
        }
    
        public String getName() {
            return name;
        }
        
        public void setUri(Uri uri) {
            this.uriString = uri.toString();
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    There are also other options for serialization (ie. Json) and you can also use them.