send objects through bundle

来源:互联网 发布:牧场数据信息管理平台 编辑:程序博客网 时间:2024/06/08 12:48

One More way to send objects through bundle is by using bundle.putByteArray
Sample code

public class DataBean implements Serializable {private Date currentTime;public setDate() {    currentTime = Calendar.getInstance().getTime(); }public Date getCurrentTime() {    return currentTime; }}

put Object of DataBean in to Bundle:

class FirstClass{public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//Your code...//When you want to start new Activity...Intent dataIntent =new Intent(FirstClass.this, SecondClass.class);            Bundle dataBundle=new Bundle();            DataBean dataObj=new DataBean();            dataObj.setDate();            try {                dataBundle.putByteArray("Obj_byte_array", object2Bytes(dataObj));            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            dataIntent.putExtras(dataBundle);            startActivity(dataIntent);}

Converting objects to byte arrays

/** * Converting objects to byte arrays */static public byte[] object2Bytes( Object o ) throws IOException {      ByteArrayOutputStream baos = new ByteArrayOutputStream();      ObjectOutputStream oos = new ObjectOutputStream( baos );      oos.writeObject( o );      return baos.toByteArray();    }

Get Object back from Bundle:

class SecondClass{DataBean dataBean;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//Your code...//Get Info from Bundle...    Bundle infoBundle=getIntent().getExtras();    try {        dataBean = (DataBean)bytes2Object(infoBundle.getByteArray("Obj_byte_array"));    } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    } catch (ClassNotFoundException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }}

Method to get objects from byte arrays:

/** * Converting byte arrays to objects */static public Object bytes2Object( byte raw[] )        throws IOException, ClassNotFoundException {      ByteArrayInputStream bais = new ByteArrayInputStream( raw );      ObjectInputStream ois = new ObjectInputStream( bais );      Object o = ois.readObject();      return o;    }

Hope this will help to other buddies.

0 0