10

i have a basic function which requires serializing in my android app. The user will add some values to an ArrayList and i want to serialize it to avoid using a database for this little option and of course TO LEARN how to serialize (i'm a begginer) because it seems useful. Anyways the user save something in the arraylist, the program shuts down, the program starts up again and the user is able to see the saved data. How can i implement this? Can you provide some code snippet or a useful link?

Thanks a lot!!

madcoderz
  • 4,423
  • 10
  • 47
  • 74
  • 1
    It should be about the same, http://stackoverflow.com/questions/3588932/problem-serializing-and-deserializing-arraylist, then you need to write to the SDcard from there. – Xorlev Jan 12 '11 at 15:06
  • After you serialize, where exactly you want to save the stuff? Options included: Preference, Db (which you rejected), Directly to File system. – xandy Jan 12 '11 at 15:07
  • Easiest thing is to serialize it to the filesystem on the SDCard. – chubbsondubs Jan 12 '11 at 15:11
  • Does every android phone have an SD card? What if the user change for a bigger SD card, all data will be lost. Can i save it in the device?, not in SD card. – madcoderz Jan 12 '11 at 15:17
  • Yes you can save it to the device or the SDCard using a FileInputStream/FileOutputStream. – chubbsondubs Jan 12 '11 at 16:00

2 Answers2

12

You can do this by custom bean class and implement Serializable to that so now when you create ArrayList<E> of that class it is Serializable.

Example:

Class dataBean implements Serializable
{
     public String name;
}

ArrayList<dataBean> dataBeanArrayList = new ArrayList();

So dataBeanArrayList is now Serializable and you can also pass this between Intent.

mtmurdock
  • 12,756
  • 21
  • 65
  • 108
Megha
  • 1,581
  • 2
  • 18
  • 33
0

I suggest using flexjson to serialize the data to a file. Then you can read that back using that library. This has several advantages over serialization which is being able to load your stream back into potential differing versions of your objects. Using ObjectInputStream you have to be very careful, and quite frankly I've never seen it work all that well.

http://flexjson.sourceforge.net

Here is a blog post how to do that:

http://wrongnotes.blogspot.com/2010/09/flexjson-meet-android.html

chubbsondubs
  • 37,646
  • 24
  • 106
  • 138
  • doesn't JSON need an internet connection? I wouldn't require that from a possible user. – madcoderz Jan 12 '11 at 15:19
  • 2
    No JSON is just a simple text format for data like XML. You can use it without an internet connection. You will need to allow your app to write to the file system. – chubbsondubs Jan 12 '11 at 15:23