Saturday, May 26, 2012

Pass Custom Object Using Parcelable: Android


Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient that Serializable, and to get around some problems with the default Java serialization scheme.
Serialization in Java is far too slow to satisfy Android’s interprocess-communication requirements. The Parcelable approach requires that you explicitly serialize the members of your class, but in the end, you get a much faster serialization of your objects.
The writeToParcel Method:
The writeToParcel method is implemented quite easy as well. The Parcel interface contains methods to write primitve java types such as string, int, etc. We can use these methods to store the object state within the parcel.
public void writeToParcel(Parcel outParcel, int flags) {
//Write data to Parcel
outParcel.writeString(message);
.....
}

For the demarshalling, we need to remember the sequence in which we have stored the fields in the parcel.
The Parcelable.Creator CREATOR field:
The CREATOR field is required for the demarshalling. As previously described, the Parcelable.Creator interface requires us to implement two methods:
public static final Parcelable.Creator 
CREATOR = new Parcelable.Creator() {
@Override
public YOUR_CLASS_NAME createFromParcel(Parcel in) {
From ParcelTo read data,Return YOUR_CLASS_NAME Object 
String message = in.readString();
.....
return new YOUR_CLASS_NAME(Params...); //YOUR_CLASS_NAME constructor
}

During the createFromParcel method we use the read methods which are provided in the Parcel to extract our state information. In the end we create a new class object with the corresponding state.

Example Pass data by implemeting Parcelable interface:
    Car.java implemeting Parcelable interface: :
package com.imrankhanandroid.PassdatausingParcelable;
import android.os.Parcel;
import android.os.Parcelable;

public class Car implements Parcelable {

    private String CarName;  
    private String companyName;  
    private int contactNum;
    public String getCarName() {  
        return CarName;  
    }  
    public void setCarName(String CarName) {  
        this.CarName = CarName;  
    }  
    public String getCompanyName() {  
        return companyName;  
    }  
    public void setCompanyName(String companyName) {  
        this.companyName = companyName;  
    }  
    public int getContactNum() {  
        return contactNum;  
    }  
    public void setcontactNum(int contactNum) {  
        this.contactNum = contactNum;  
    }  
    public static final Parcelable.Creator CREATOR =new Creator() {

  @Override
  public Car createFromParcel(Parcel source) {
   // TODO Auto-generated method stub
   Car mCar=new Car();
   mCar.CarName=source.readString();
   mCar.companyName=source.readString();
   mCar.contactNum=source.readInt();
   return mCar;
  }

  @Override
  public Car[] newArray(int size) {
   // TODO Auto-generated method stub
   return new Car[size];
  }
 };
 @Override
 public int describeContents() {
  // TODO Auto-generated method stub
  return 0;
 }

 @Override
 public void writeToParcel(Parcel parcel, int flags) {
  // TODO Auto-generated method stub
  parcel.writeString(CarName);
  parcel.writeString(companyName);
  parcel.writeInt(contactNum);
 }

}

    ObjectSenderActivity.java Activity: :
package com.imrankhanandroid.PassdatausingParcelable;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ObjectSenderActivity extends Activity {
 private Button sButton;  
    public  final static String PAR_KEY = "com.imrankhanandroid.PassdatausingParcelable.par";  

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sButton = (Button)findViewById(R.id.btnsend); 
        sButton.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    PacelableMethod();
   }
  });
    }
  //PacelablePassing an object method
    public void PacelableMethod(){  
        Car mCar = new Car();  
        mCar.setCarName("jaguar xf sedan");  
        mCar.setCompanyName("jaguar");  
        mCar.setcontactNum(123456789);  
        Intent mIntent = new Intent(this,ObjectReceiverActivity.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putParcelable(PAR_KEY, mCar);  
        mIntent.putExtras(mBundle);  
          
        startActivity(mIntent);  
    }  
}

    ObjectReceiverActivity.java Activity: :
package com.imrankhanandroid.PassdatausingParcelable;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;


public class ObjectReceiverActivity extends Activity {
 TextView txtview;
  /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.maintwo);
       //Get person object from Intent deliver to ObjectReceiverActivity
       Car mCar = (Car)getIntent().getParcelableExtra(ObjectSenderActivity.PAR_KEY);
       txtview=(TextView)findViewById(R.id.txtrev);
       txtview.append(Html.fromHtml("
Car Name :"+mCar.getCarName() +"
Company Name :"+mCar.getCompanyName() +"
Contact Num :"+mCar.getContactNum() )); } }

    src/layout/main.xml: :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Welcome to Imran Khan's Blog."
    android:gravity="center"  
    android:layout_marginTop="80dp"
    />  
    <TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Object Sender Activity"
    android:gravity="center"  
    android:layout_marginTop="80dp"
    /> 
<Button  
    android:id="@+id/btnsend"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="Send Parcelable Object" 
    android:textSize="25px" 
    android:layout_marginTop="15dp"
/> 
</LinearLayout>


    src/layout/maintwo.xml: :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Obecjt Reciver Activity"
    android:gravity="center"  
    android:layout_marginTop="80dp"
    android:textSize="25px"
    /> 
    <TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Data Recived from Sender Activity:-"
    android:layout_marginTop="80dp"
    android:id="@+id/txtrev"
    android:textSize="25px"
    /> 
</LinearLayout>


    AndroidManifest.xml: :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.imrankhanandroid.PassdatausingParcelable"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="7" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".ObjectSenderActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ObjectReceiverActivity"></activity>
    </application>
</manifest>

Download Source Code: PassdatausingParcelable









0 comments:

Post a Comment

 
Powered by Blogger