Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

android - Read an ArrayList from Internal Storage

I have an Android application and I would like to read and write an ArrayList<MyClass> to the Internal Storage.

The writing part works (I believe, haven't tested it yet :-) ) :

ArrayList<MyClass> aList;

    public void saveToInternalStorage() {
    try {
        FileOutputStream fos = ctx.openFileOutput(STORAGE_FILENAME, Context.MODE_PRIVATE);
        fos.write(aList.toString().getBytes());
        fos.close();
    }
    catch (Exception e) {
        Log.e("InternalStorage", e.getMessage());
    }
}

But what I want to do now is read the whole ArrayList from the Storage and return it as an ArrayList like so:

public ArrayList<MyClass> readFromInternalStorage() {
        ArrayList<MyClass> toReturn;
        FileInputStream fis;
        try {
            fis = ctx.openFileInput(STORAGE_FILENAME);

            //read in the ArrayList
            toReturn = whatever is read in...

            fis.close();
        } catch (FileNotFoundException e) {
            Log.e("InternalStorage", e.getMessage());
        } catch (IOException e) {
            Log.e("InternalStorage", e.getMessage()); 
        }
        return toReturn
}

I've never read in a file with Android before, so I don't know if this is even possible. But is there A way I can read in my custom ArrayList?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you have to serialize/deserialize your object:

Your MyClass must implments Serializable and all the member inside MyClass must be serializable

 public void saveToInternalStorage() {
        try {
            FileOutputStream fos = ctx.openFileOutput(STORAGE_FILENAME, Context.MODE_PRIVATE);
            ObjectOutputStream of = new ObjectOutputStream(fos);
            of.writeObject(aList);
            of.flush();
            of.close();
            fos.close();
        }
        catch (Exception e) {
            Log.e("InternalStorage", e.getMessage());
        }
}

to deserialize the object:

public ArrayList<MyClass> readFromInternalStorage() {
    ArrayList<MyClass> toReturn;
    FileInputStream fis;
    try {
        fis = ctx.openFileInput(STORAGE_FILENAME);
        ObjectInputStream oi = new ObjectInputStream(fis);
        toReturn = oi.readObject();
        oi.close();
    } catch (FileNotFoundException e) {
        Log.e("InternalStorage", e.getMessage());
    } catch (IOException e) {
        Log.e("InternalStorage", e.getMessage()); 
    }
    return toReturn
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...