user1212520
user1212520

Reputation: 501

write/save an array of custom objects android java

I have been using this code:

                 public void saveCredits(int myInt) {
         try {
            OutputStream fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
            DataOutputStream dis = new DataOutputStream(fos);
            dis.writeInt(myInt);
            fos.flush();
            fos.close();
         }
         catch (IOException e) {
             System.out.println(e); 
         }
      }

How do I modify it in the simplest way to also write an array of custom objects such as houses(String name, int cost, Address address)

Upvotes: 0

Views: 750

Answers (2)

myself
myself

Reputation: 502

Easiest way with DataOutputStream is to:

  1. store array size
  2. then items themselves

Like this:

DataOutputStream out = ... ;
out.writeInt(items.length);
for (Item item : items) {
    out.writeUTF(item.someString());
    out.writeFloat(item.someFloat());
}

Loading such an array is easy too:

DataInputStream in = ... ;
int length = in.readInt();
Item[] items = new Item[length];
for (int i = 0; i < length; ++i) {
    items.add(new Item(in.readUTF(), in.readFloat()));
}

Upvotes: 1

ngesh
ngesh

Reputation: 13501

Use ObjectOutPutStream and method writeObject().. Preciseley you need to Serialize and Deserialize your Objects.. more here

Upvotes: 0

Related Questions