Search code examples
androiddata-storage

Not reading or writing to internal storage android


I'm trying to store a Map into android's internal storage.

My code:

    private void saveFavorite(){
    LinkedHashMap<String, LinkedList<MyCustomObject>> favorites = new LinkedHashMap<String, LinkedList<MyCustomObject>>();

    try{
        InputStream file = openFileInput(PATH);
        BufferedInputStream buffer = new BufferedInputStream( file );
        ObjectInput input = new ObjectInputStream ( buffer );
        try{
            Object o = input.readObject();
            if(o instanceof LinkedHashMap<?, ?>)
                favorites = (LinkedHashMap<String, LinkedList<MyCustomObject>>)o;
        }
        finally{
            input.close();
        }
    }
    catch(ClassNotFoundException ex){
    }
    catch(IOException ex){
    }

    String favoriteName = "asd";


    favorites.put(favoriteName, myobject);


    FileOutputStream fos;
    try {
        fos = openFileOutput(PATH, MODE_APPEND);
        BufferedOutputStream buffer = new BufferedOutputStream( fos );
        ObjectOutput output = new ObjectOutputStream( buffer );
        try{
            output.writeObject(favorites);
        }finally{
            output.close();
        }
    }catch(IOException ex){
    }
}

MyCustomObject implements Serializable

While debugging I don't see any problem. It seems it reads an empty map, then writes the map with a value but when I read it again, map is empty.

Help please.

UPDATE: I have found inside /data/data/my_project_package_structure/files/ a file called like my var PATH. It's growing in size each time I call my save method so I think it writes well but I don't know what I'm doing wrong.


Solution

  • try {
        **fos = openFileOutput(PATH, MODE_APPEND);**
        BufferedOutputStream buffer = new BufferedOutputStream( fos );
    

    Should be

        **fos = openFileOutput(PATH, MODE_PRIVATE);**