Wednesday, 21 October 2015

Sending Object from one Activity to other Activity using Parcelable


Passing custom object is not like a passing simple variable. Whenever you want to pass custom object between activities you need to implement Parcelable or Serializable. For the serialization you can follow this post.

Classes implementing the Parcelable interface must also have a non-null static field called CREATOR of a type that implements the Parcelable.Creator interface.
For More information about Parcelable follow this post.

Implementation:-

UserActivity.java:-

package com.test.parcelable;  
 import android.content.Intent;  
 import android.os.Bundle;  
 import android.support.v7.app.AppCompatActivity;  
 import android.view.View;  
 import android.widget.EditText;  
 /**  
  * Created by anay.dwivedi on 22-Oct-15.  
  */  
 public class UserActivity extends AppCompatActivity implements View.OnClickListener {  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_user);  
   }  
   @Override  
   public void onClick(View v) {  
     validation();  
   }  
   private void validation() {  
     EditText nameEditText = (EditText) findViewById(R.id.edtvUserName);  
     EditText ageEditText = (EditText) findViewById(R.id.edtvAge);  
     EditText addressEditText = (EditText) findViewById(R.id.edtvAddress);  
     EditText stateEditText = (EditText) findViewById(R.id.edtvState);  
     if (isEmpty(nameEditText)) {  
       nameEditText.setError(getString(R.string.field_empty));  
     } else if (isEmpty(ageEditText)) {  
       ageEditText.setError(getString(R.string.field_empty));  
     } else if (isEmpty(addressEditText)) {  
       stateEditText.setError(getString(R.string.field_empty));  
     } else if (isEmpty(stateEditText)) {  
       stateEditText.setError(getString(R.string.field_empty));  
     } else {  
       Student student = new Student(nameEditText.getText().toString(), Integer.parseInt(ageEditText.getText().toString()), addressEditText.getText().toString(), stateEditText.getText().toString());  
       Intent i = new Intent(getBaseContext(), SecondActivity.class);  
       i.putExtra("studentObject", student);  
       startActivity(i);  
     }  
   }  
   public boolean isEmpty(EditText editText) {  
     return editText.getText().toString().length() <= 0;  
   }  
 }  
activity_user.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".UserActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/tilUserName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edtvUserName"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/name"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/tilAge"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edtvAge"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/age"
            android:inputType="number"
            />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/tilAddress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edtvAddress"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/address"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/tillState"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edtvState"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/state"/>
    </android.support.design.widget.TextInputLayout>
    <Button
        android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:onClick="onClick"
        android:layout_height="wrap_content"
        android:text="Submit"
        />
</LinearLayout>
Student.java

package com.test.parcelable;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by anay.dwivedi on 22-Oct-15.
 * A basic object that can be parcelled
 */
public class Student implements Parcelable {

    private String name;
    private String address;
    private int age;
    private String state;


    /**
     * Constructor to use when re-constructing object
     * from a parcel
     *
     * @param in a parcel from which to read this object
     */
    protected Student(Parcel in) {
        name = in.readString();
        address = in.readString();
        age = in.readInt();
        state = in.readString();
    }

    public Student(String name, int age, String address, String state) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.state = state;
    }

    /**
     * This field is needed for Android to be able to
     * create new objects, individually or as arrays.
     * <p/>
     */
    public static final Creator<Student> CREATOR = new Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel in) {
            return new Student(in);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };


    @Override
    public int describeContents() {
        return 0;
    }

    // We just need to write each field into the
    // parcel. When we read from parcel, they
    // will come back in the same order
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeString(address);
        dest.writeInt(age);
        dest.writeString(state);
    }

    /**
     * standard getter
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name {@link #name}
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * standard getter
     *
     * @return address
     */
    public String getAddress() {
        return address;
    }

    /**
     * @param address {@link #address}
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * standard getter
     *
     * @return age
     */
    public int getAge() {
        return age;
    }


    /**
     * @param age {@link #age}
     */
    public void setAge(int age) {
        this.age = age;
    }

    /**
     * standard getter
     *
     * @return state
     */
    public String getState() {
        return state;
    }


    /**
     * @param state {@link #state}
     */
    public void setState(String state) {
        this.state = state;
    }
}
SecondActivity.java

package com.test.parcelable;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
/**
 * Created by anay.dwivedi on 22-Oct-15.
 */
public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        TextView nameTextView=(TextView)findViewById(R.id.txtName);
        TextView ageTextView=(TextView)findViewById(R.id.txtAge);
        TextView addressTextView=(TextView)findViewById(R.id.txtAddress);
        TextView stateTextView=(TextView)findViewById(R.id.txtState);
        Student student =getIntent().getParcelableExtra("studentObject");
        if(student!=null)
        {
            nameTextView.setText(String.format("Name :  %s", student.getName()));
            ageTextView.setText(String.format("Age : %d", student.getAge()));
            addressTextView.setText(String.format("Address : %s", student.getAddress()));
            stateTextView.setText(String.format("State  : %s", student.getState()));
        }

    }
}
strings.xml
<resources>
    <string name="app_name">Parcelable</string>
    <string name="name">Name</string>
    <string name="age">Age</string>
    <string name="address">Address</string>
    <string name="state">State</string>
    <string name="field_empty">Field Can Not be Empty</string>

</resources>
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>
styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

No comments:

Post a Comment