0

I have an ArrayList like this one:

savedQuestions = new ArrayList<String>();

How to save it to Text file in Android local Storage When Click button ?

galath
  • 5,717
  • 10
  • 29
  • 41
sabish
  • 31
  • 1
  • 8

1 Answers1

0

Even though the ArrayList class is serializable by default you will have to make the Figur class (and any classes it uses) Serializable as well. this would probably mean something like:

class Figur implements Serializable {
    // To handle the version of your class
    private static final int serialVersionUID = 1L;

    // Your code would go here
}

And then you have to serialize with something like:

ObjectOutputStream fileOut = new ObjectOutputStream(new FileOutputStream("file"));
fileOut.writeObject(list);
fileOut.close();

And to deserialize:

ObjectInputStream fileIn = new ObjectInputStream(new FileInputStream("file"));
list = (ArrayList) fileIn.readObject();
fileIn.close();

Also note, when you write to the file, you want to append to the previous items in the file and not overwrite (errase) them. I think either objectOutputStream() or writeObject() probably has an optional argument in it to allow it to append instead of overwrite. Example: writeObject(list, true) instead of writeObject(list). You'll have to research this to determine the correct way to do it.

Also, if you cant get serialization to work, you can instead store the values for "circle, rect, line, color, fill" that makes up one figur object in the file as a single line with a delimiter such as 'comma'' between them. Then read a line back from the file and use those values to make a populated figur object. Example: Store these strings in the file: 3,6,7,red,4 6,3,4,blue,8

Then when you read the contents of the file, build your objects:

Figur figure1 = new Figur("3","6","7","red","4");
Figur figure2 = new Figur("6","3","4","blue","8");

ArrayList<Figur> figurs =new ArrayList<Figur>();
figurs.add(figure1);
figurs.add(figure2);

Its not as efficient as using serialization, but it gets the job done and the contents of the file is in a human readable form.

From the link https://community.oracle.com/thread/1193052?start=0&tstart=0

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73