Friday, 30 October 2015

Read Android PhoneBook(native) Contact

I am going to show you how to read list of phone book contact(Name, Email and profile image). This is simple demo to read contacts not a whole implementation. you can integrate below code when you are going to use CursorLoader for Reading contacts.

1.Request Permission to Read the Provider

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

2.Define the code that sends a query to the provider.

Constructing the query
private static final String[] PROJECTION = new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
            ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Phone.PHOTO_URI};

Read contact
private void readContact() {
        List<Contact> contacts = new ArrayList<>();
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
        if (cursor != null) {
            try {
                final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                final int uriIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI);
                while (cursor.moveToNext()) {
                    Contact contact = new Contact();
                    contact.setName(cursor.getString(nameIndex));
                    contact.setPhoneNumber(cursor.getString(numberIndex));
                    contact.setUri(cursor.getString(uriIndex));
                    contacts.add(contact);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();
            }
        }
    }

if you added multiple phone number in single contact you can see in list as a separate contact row.






MultiChoice ListView with Custom Adapter

I am writing code for multiple choice list. User easily select multiple item from list after that they can see how many item selected or not. When user will tap on Show Selected Android version easily can get the data in activity.




MainActivity.java

package com.multiplechoicelistview.example;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private String[] androidVersions = {"Cupcake 1.5", "Donut 1.6 ", "Eclair 2.0", "Froyo 2.2",
            "Gingerbread  2.3", "Honeycomb 3.0", "Ice Cream Sandwich 4.0", "Jelly Bean 4.1",
            "KitKat 4.4", "Lollipop 5.0", "Marshmallow 6.0"};
private  VersionCustomAdapter mVersionCustomAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        displayListView();
    }

    /*
    *show ListView
    * */
    private void displayListView() {
        View footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
        ArrayList<AndroidVersionName> versionNameArrayList = new ArrayList<>();
        int versionSize= androidVersions.length;
        for (int versionCount = 0; versionCount <versionSize ; versionCount++) {
            AndroidVersionName androidVersionName = new AndroidVersionName();
            androidVersionName.setVersionName(androidVersions[versionCount]);
            versionNameArrayList.add(androidVersionName);
        }
         mVersionCustomAdapter = new VersionCustomAdapter(this, R.layout.version_row_layout, versionNameArrayList);
        ListView listView = (ListView) findViewById(R.id.lvVersionList);
        listView.setAdapter(mVersionCustomAdapter);
        listView.addFooterView(footerView);

        listView.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                AndroidVersionName androidVersionName = (AndroidVersionName) parent.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(),
                        "Clicked on Row: " + androidVersionName.getVersionName(), Toast.LENGTH_LONG)
                        .show();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnSelectedList:
                StringBuffer responseText = new StringBuffer();
                responseText.append("Selected Text...\n");

                ArrayList<AndroidVersionName> selectedVersionNameList= mVersionCustomAdapter.getSelectedList();
                int selectedListSize=selectedVersionNameList.size();
                for (int selectedCount = 0; selectedCount < selectedListSize; selectedCount++) {
                    AndroidVersionName androidVersionName = selectedVersionNameList.get(selectedCount);
                    if (androidVersionName.isSelected()) {
                        responseText.append("\n" + androidVersionName.getVersionName());
                    }
                }

                Toast.makeText(getApplicationContext(), responseText,
                        Toast.LENGTH_LONG).show();
                break;
        }


    }


}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <include
        layout="@layout/content_main"
        />
</android.support.design.widget.CoordinatorLayout>

content_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#ffeeeeee"
              android:gravity="center"
              android:orientation="vertical"
              android:paddingTop="?attr/actionBarSize">


    <ListView
        android:id="@+id/lvVersionList"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

</LinearLayout>

footer_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <Button
        android:id="@+id/btnSelectedList"
        android:layout_width="match_parent"
        android:onClick="onClick"
        android:layout_height="wrap_content"
        android:text="@string/show_selection" />

</LinearLayout>

version_row_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="6dip">

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:textColor="#ff00bb88" />

    <TextView
        android:id="@+id/tvVersionName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/checkBox1"
        android:layout_alignBottom="@id/checkBox1"
        android:layout_toRightOf="@id/checkBox1"
        android:text="textview"
        android:textColor="#FF00FF" />

</RelativeLayout>

AndroidVersionName.java

package com.multiplechoicelistview.example;

/**
 * Created by Anay on 10/31/2015.
 */
public class AndroidVersionName {
    private String versionName;
    private boolean isSelected;

    public boolean isSelected() {
        return isSelected;
    }

    public void setIsSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }

    public String getVersionName() {
        return versionName;
    }

    public void setVersionName(String versionName) {
        this.versionName = versionName;
    }


}

VersionCustomAdapter.java

package com.multiplechoicelistview.example;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Anay on 10/31/2015.
 */
public class VersionCustomAdapter extends ArrayAdapter<AndroidVersionName> {

    private ArrayList<AndroidVersionName> mVersionNameArrayLists;
    LayoutInflater mLayoutInflater;
    private Context mContext;

    public VersionCustomAdapter(Context context, int textViewResourceId,
                                ArrayList<AndroidVersionName> versionNameArrayLists) {
        super(context, textViewResourceId, versionNameArrayLists);
        this.mVersionNameArrayLists = versionNameArrayLists;
        this.mContext = context;
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public ArrayList<AndroidVersionName> getSelectedList() {
        return mVersionNameArrayLists;
    }

    private class ViewHolder {
        TextView versionNameTextView;
        CheckBox checkBox;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        Log.v("ConvertView", String.valueOf(position));

        if (convertView == null) {
            holder = new ViewHolder();

            convertView = mLayoutInflater.inflate(R.layout.version_row_layout, null);
            holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
            holder.versionNameTextView = (TextView) convertView.findViewById(R.id.tvVersionName);

            holder.checkBox.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    CheckBox checkBox = (CheckBox) view;
                    AndroidVersionName androidVersionName = (AndroidVersionName) checkBox.getTag();
                    androidVersionName.setIsSelected(checkBox.isChecked());
                }
            });
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        AndroidVersionName androidVersionName = mVersionNameArrayLists.get(position);

        holder.versionNameTextView.setText(androidVersionName.getVersionName());
        holder.checkBox.setChecked(androidVersionName.isSelected());

        holder.checkBox.setTag(androidVersionName);

        return convertView;
    }

}




JSON data parsing by using GSON library


Activity transition animation during navigation from one activity to another activity

When you navigate from one activity to another activity the transition between activities can be animate

How to get call back from AsyncTask or any other class


I am creating AsyncTask(Sample) for getting some data from server after that get callback to our activity. For this purpose I am writing interface and LoaderManager class.

MainActivity.java

package demo.com.applicationcallback;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnGetCallBack:
                getCallBackFromLoaderManager();
                break;
        }
    }

    private void getCallBackFromLoaderManager() {
        /*if you want to pass some data in LoaderManager
         class you can pass in Constructor*/
        LoaderManager loaderManager = new LoaderManager(new CustomCallback() {

            @Override
            public void success(String message) {
               /* if successfully get data from server, control gets back here
                you can write code here as per the your requirement*/
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void fail(String message) {
                /*fail due to some reason control gets back here according to your requirement write your code*/
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
        loaderManager.execute(/*here we can pass some data as per the our requirement*/);
    }
}

LoaderManager.java

package demo.com.applicationcallback;

import android.os.AsyncTask;

public class LoaderManager extends  AsyncTask<String, Void, Boolean> {

    private CustomCallback mCustomCallback;

    public LoaderManager(CustomCallback customCallback) {
        this.mCustomCallback= customCallback;
    }


    @Override
    protected Boolean doInBackground(String... params) {
        // write  code for getting data from server
        return true;
    }

    @Override
    protected void onPreExecute() {
        //write code show progress bar or some custom loading indicator etc...
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {

        if(aBoolean){
            mCustomCallback.success("Get data Successfully");
        }else {
            mCustomCallback.fail("Failure due to some reason");
        }
    }
}

CustomCallback.java

package demo.com.applicationcallback;

public interface CustomCallback {
    public void success(String message);
    public void fail(String message);
}

activity_main.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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:orientation="vertical"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnGetCallBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="initiateCallback" />

    <TextView
        android:id="@+id/tvShowMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>









Measure Device Density Idependence

There are multiple devices having different densities, So this is way by which we can measure which devices fall in which density.
Screen density is a ratio of resolution and display size.


Different sizes and densities are roughly categorized into the different size and density groups.

MainActivity.java


package com.demo.density.independence;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import static android.widget.Toast.LENGTH_LONG;
import static android.widget.Toast.makeText;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getDensityIndependenceDevice();
    }

    private void getDensityIndependenceDevice() {
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int density = displayMetrics.densityDpi;
        switch (density){
            case DisplayMetrics.DENSITY_LOW:
                showDensity("DENSITY_LOW",density);
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                showDensity("DENSITY_MEDIUM", density);
                break;
            case DisplayMetrics.DENSITY_HIGH:
                showDensity("DENSITY_HIGH",density);
                break;
            case DisplayMetrics.DENSITY_XHIGH:
                showDensity("DENSITY_XHIGH", density);
                break;
            case DisplayMetrics.DENSITY_XXHIGH:
                showDensity("DENSITY_XXHIGH", density);
                break;
            case DisplayMetrics.DENSITY_XXXHIGH:
                showDensity("DENSITY_XXXHIGH", density);
                break;
            case DisplayMetrics.DENSITY_560:
                showDensity("DENSITY_560", density);
                break;
            case DisplayMetrics.DENSITY_420:
                showDensity("DENSITY_420", density);
                break;
        }

        float densityPxPerDp = displayMetrics.density;
        float densityPxPerSp = displayMetrics.scaledDensity;
        float densityBucketDpi = displayMetrics.densityDpi;
        float xdpi = displayMetrics.xdpi;
        float ydpi = displayMetrics.ydpi;

    }

    private void showDensity(String densityString, int density) {
        TextView densityTextView= (TextView) findViewById(R.id.tvDensity);
        densityTextView.setText(String.format("%s... Density is %s", densityString, String.valueOf(density)));
        makeText(this, densityString + "... Density is " + String.valueOf(density), LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main"
        />

</android.support.design.widget.CoordinatorLayout>

content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/tvDensity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black" />

</RelativeLayout>



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() &lt;= 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>