Serialization in Android – A Simple example.

By | July 19, 2012

Serializing a class file provides a fast and efficeint way to store information produced by your application!

What is serialization?

Serialization is essentually taking a screenshot of a class file and its contents. For example, lets say you have the following class:


package com.coderzheaven.pack;

import java.io.Serializable;

public class Person implements Serializable //Added implements Serializable
{
	String name="";
	private String number="";
	private String address=""; 
	private static final long serialVersionUID = 46543445; 

	public void setName(String name)
    {
    	this.name = name;
    }
    
    public void setNumber(String number)
    {
    	this.number = number;
    }

    public void setAddress(String address)
    {
    	this.address = address;
    }
    
    public String getName()
    {
    	return name;
    }
    	
    public String getNumber()
    {
    	return number;
    }
    	
    public String getAddress()
    {
    	return address;
    }
}

Now we will save this data to a file in the SDCARD.
Make sure to add the write permission in the AndroidManifest.xml file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Now the Activity class which does the saving and retrieving of the object.

package com.coderzheaven.pack;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class SerializationDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Person person = new Person();
        person.setName("CoderzHeaven");
        person.setAddress("CoderzHeaven India");
        person.setNumber("1234567890"); 
        
        //save the object
        saveObject(person);
        
        // Get the Object
        Person person1 = (Person)loadSerializedObject(new File("/sdcard/save_object.bin")); //get the serialized object from the sdcard and caste it into the Person class.
        System.out.println("Name : " + person1.getName());
    }
    
    public void saveObject(Person p){
    	 try
         {
         	ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/sdcard/save_object.bin"))); //Select where you wish to save the file...
         	oos.writeObject(p); // write the class as an 'object'
         	oos.flush(); // flush the stream to insure all of the information was written to 'save_object.bin'
         	oos.close();// close the stream
         }
         catch(Exception ex)
         {
         	Log.v("Serialization Save Error : ",ex.getMessage());
         	ex.printStackTrace();
         }
    }
    
    public Object loadSerializedObject(File f)
    {
        try
        {
        	ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
        	Object o = ois.readObject();
        	return o;
        }
        catch(Exception ex)
        {
    	Log.v("Serialization Read Error : ",ex.getMessage());
        	ex.printStackTrace();
        }
        return null;
    }
}

Serialization pull out file.

These are the Rules of Serialization

    Always use variables that can actually be serialized
    Never change the class files source after you serialize a class file from it
    Do not use super large int[] arrays (bug described below)

Now check the Logcat for the output.
Please leave your comments on this example.

Download the sample project of this demo from here.

In the next post we will see how to read a serialized object from the raw folder.

One thought on “Serialization in Android – A Simple example.

  1. Mukhen

    it’s been late, so it’s only purposed to store information in the phone (internal m/r, sd card, sqlite), that’s what serialisation used for?
    Or something else, I missed?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *