Retrofit Introduction

Internet Permission in Android’s Manifest

<uses-permission android:name=”android.permission.INTERNET”/>

Define Dependency: Gradle

dependencies {
// Retrofit & OkHttp
compile ‘com.squareup.retrofit2:retrofit:2.1.0’
compile ‘com.squareup.retrofit2:converter-gson:2.1.0’
}

Define Service Interface / API Interface :

public interface GitHubService {
@GET(“users/{user}/repos”)
Call<List<GitHubRepo>> reposForUser(@Path(“user”) String username);
}

Service Generator

This is the heart. It defines a method to create a basic REST client for a given class/interface which returns a service class from the interface.

public class ServiceGenerator {

public static String apiBaseUrl = “https://api.github.com/&#8221;;

private static Retrofit retrofit;

private static Retrofit.Builder builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(apiBaseUrl);

private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

public static void changeApiBaseUrl(String newApiBaseUrl) {
apiBaseUrl = newApiBaseUrl;

builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient())
.baseUrl(apiBaseUrl);
}

public static <S> S createService(Class<S> serviceClass) {

builder.client(httpClient.build());
retrofit = builder.build();

return retrofit.create(serviceClass);
}

public static Retrofit retrofit() {
return retrofit;
}
}

Retrofit’s Retrofit-Builder to create a new REST client with the given API base url (BASE_URL).

Why Is Everything Declared Static Within the Servicegenerator?

We want to use the same OkHttpClient throughout the app to just open one socket connection that handles all the request and responses including caching and many
more.

And because we use the OkHttpClient throughout this class, we need to make all fields and methods static.

It’s common practice to just use one OkHttpClient instances to reuse open socket connection.

• [x] What is Retrofit
• [x] Why use Retrofit
• [x] How to define a service interface representing an API endpoint
• [x] How to create an instance of the service interface
• [x] How to execute an API request

 

 

 

6 Download data from Internet and Parse the data

Video 45 – Downloading data from Internet

XML Viewer :

http://codebeautify.org/xmlviewer

In Android, use Asynchronous programming for doing these kind of tasks. The idea is not to block the UI waiting for something to complete.

Asynchronous – we send off a request to do something, but we don’t wait on the response. But we ask the platform to inform us when the task gets completed.

Android has given us a mechanism – AsyncTask

We are going to create a private inner class that’s part of Main Activity class.

 

 

 

5 Android Layouts and Views

Video 40 : How to layout our Designs

We will be developing a simple calculator app.

In this app, we will make use of LinearLayout.

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/help_instructions"
        android:gravity="center"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:ems="10"
        android:id="@+id/editOperand1"
        android:layout_marginTop="25dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:ems="10"
        android:id="@+id/editOperand2" />
</LinearLayout>

 

Video 41 : Adding Buttons to Calculator app – Nested LinearLayout

You can have layouts within layouts, and you can build up very complex interfaces by doing that.

String resources – don’t hardcode string values in layout files. Instead use string resources.

Complete layout file for Simple Calculator app :

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/help_instructions"
        android:gravity="center"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:ems="10"
        android:id="@+id/editOperand1"
        android:layout_marginTop="25dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:ems="10"
        android:id="@+id/editOperand2" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+"
            android:id="@+id/btnAddition"
            style="?android:attr/buttonStyleSmall" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="-"
            android:id="@+id/btnSubtraction"
            style="?android:attr/buttonStyleSmall" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="/"
            android:id="@+id/btnDivision"
            style="?android:attr/buttonStyleSmall" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="*"
            android:id="@+id/btnMultiplication"
            style="?android:attr/buttonStyleSmall" />

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CLR"
            android:id="@+id/btnClear" />

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/result_description"
        android:id="@+id/textView2"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="0.00"
        android:id="@+id/txtResult"
        android:gravity="center" />

</LinearLayout>

 

Video 42 : Implementing Calculator Functionality  – Button clicks handling

Say, we want implement addition functionality when ‘+’ button is clicked.

btnAddition.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if((operand1.getText().length()>0) && (operand2.getText().length()>0)) {
            double oper1 = Double.parseDouble(operand1.getText().toString());
            double oper2 = Double.parseDouble(operand2.getText().toString());

            double theResult = oper1 + oper2;
            txtResult.setText(Double.toString(theResult));
        } else {
            Toast.makeText(MainActivity.this, "Please enter numbers in both operand fields", Toast.LENGTH_LONG).show();
        }

    }
});

 

 Video 43 : Adding CLR or reset functionality

In this video, we are going to add CLR button. When it is pressed, the result will reset to 0.0.

Complete Java code :

public class MainActivity extends AppCompatActivity {

    private EditText operand1;
    private EditText operand2;
    private Button btnAddition;
    private Button btnSubtraction;
    private Button btnDivision;
    private Button btnMultiplication;
    private Button btnClear;
    private TextView txtResult;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        operand1 = (EditText) findViewById(R.id.editOperand1);
        operand2 = (EditText) findViewById(R.id.editOperand2);
        btnAddition = (Button) findViewById(R.id.btnAddition);
        btnSubtraction = (Button) findViewById(R.id.btnSubtraction);
        btnDivision = (Button) findViewById(R.id.btnDivision);
        btnMultiplication = (Button) findViewById(R.id.btnMultiplication);
        btnClear = (Button) findViewById(R.id.btnClear);

        txtResult = (TextView) findViewById(R.id.txtResult);

        btnAddition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if((operand1.getText().length()>0) && (operand2.getText().length()>0)) {
                    double oper1 = Double.parseDouble(operand1.getText().toString());
                    double oper2 = Double.parseDouble(operand2.getText().toString());

                    double theResult = oper1 + oper2;
                    txtResult.setText(Double.toString(theResult));
                } else {
                    Toast.makeText(MainActivity.this, "Please enter numbers in both operand fields", Toast.LENGTH_LONG).show();
                }

            }
        });

        btnSubtraction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if((operand1.getText().length()>0) && (operand2.getText().length()>0)) {
                    double oper1 = Double.parseDouble(operand1.getText().toString());
                    double oper2 = Double.parseDouble(operand2.getText().toString());

                    double theResult = oper1 - oper2;
                    txtResult.setText(Double.toString(theResult));
                } else {
                    Toast.makeText(MainActivity.this, "Please enter numbers in both operand fields", Toast.LENGTH_LONG).show();

                }

            }
        });

        btnDivision.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if((operand1.getText().length()>0) && (operand2.getText().length()>0)) {

                    double oper1 = Double.parseDouble(operand1.getText().toString());
                    double oper2 = Double.parseDouble(operand2.getText().toString());

                    double theResult = oper1 / oper2;
                    txtResult.setText(Double.toString(theResult));
                } else {
                    Toast.makeText(MainActivity.this, "Please enter numbers in both operand fields", Toast.LENGTH_LONG).show();

                }

            }
        });

        btnMultiplication.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if((operand1.getText().length()>0) && (operand2.getText().length()>0)) {

                    double oper1 = Double.parseDouble(operand1.getText().toString());
                    double oper2 = Double.parseDouble(operand2.getText().toString());

                    double theResult = oper1 * oper2;
                    txtResult.setText(Double.toString(theResult));
                } else {
                    Toast.makeText(MainActivity.this, "Please enter numbers in both operand fields", Toast.LENGTH_LONG).show();

                }

            }
        });

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                operand1.setText("");
                operand2.setText("");
                txtResult.setText("0.00");
                operand1.requestFocus();

            }
        });

    }

    @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);
    }
}

 

 

4 Views and Layouts

Video 24 : Setting up Button Click Counter app

Create a new project, called Button Click Counter.

Just a bit of discussion related to Android Monitor window that shows at the bottom of the edit window. Logcat, Memory, CPU usage, Network usage, etc.

Adding a Toast message :

Toast toastMessage = Toast.makeText(this, "Settings option is clicked!!", Toast.LENGTH_LONG);
toastMessage.show();

 

Video 25 : Adding a Button

Android uses Event-driven programming.

Adding a Button in Layout.

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="My Button"
    android:id="@+id/button"
    android:layout_below="@+id/textView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="31dp" />

All the UI elements are nothing but Views – an element that forms part of a layout.

 

Video 26 : Button click event handling

When you are actually designing your layout, you use the design view. Design or Text screens are used to design your layout.

But, the actual behavior when we do something is taken care in Java code. The design view and back-end java code is interlinked.

Design layout – how things look.
Code – how things actually behave / the functionality.

setContentView(R.layout.activity_main);

this code links the Java code with the layout file

We need a way to access the elements that are in the layout file in the Java code :

that's using the concept of ID's.

android:id="@+id/textView"  -- id for TextView
android:id="@+id/button" -- id for Button

Linking the views from the layout file to the Java code :

ourButton = (Button) findViewById(R.id.button);
ourMessage = (TextView) findViewById(R.id.textView);

View.OnClickListener ourOnClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        numTimesClicked = numTimesClicked + 1;
        String result = "The button got tapped " + numTimesClicked + " time";
        if(numTimesClicked != 1) {
            result += "s...";
        }
        ourMessage.setText(result);
    }
};

ourButton.setOnClickListener(ourOnClickListener);

Full code : Button Click Counter

Layout XML file ( activity_main.xml)

<RelativeLayout 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:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView"
        android:layout_marginTop="31dp"
        android:text="My Button" />

</RelativeLayout>

Menu file : (menu_main.xml)

<menu 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"
    tools:context=".MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>

Java code : MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Button ourButton;
    private TextView ourMessage;
    private int numTimesClicked = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ourButton = (Button) findViewById(R.id.button);
        ourMessage = (TextView) findViewById(R.id.textView);

        View.OnClickListener ourOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                numTimesClicked = numTimesClicked + 1;
                String result = "The button got tapped " + numTimesClicked + " time";
                if(numTimesClicked != 1) {
                    result += "s...";
                }
                ourMessage.setText(result);
            }
        };
        ourButton.setOnClickListener(ourOnClickListener);
    }

    @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) {
            Toast toastMessage = Toast.makeText(this, "Text value is now " + ourMessage.getText(), Toast.LENGTH_LONG);
            toastMessage.show();
            numTimesClicked = 0;

            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

 

3 Hello World App

https://www.udemy.com/android-marshmallow-java-app-development-course/learn/v4/t/lecture/3608134

Video 18 : First Android application :

From starter screen -> Click on Start a New Android Studio Project ->

Here enter :

  • your App name – this name is as it shows in home screen, apps list
  • company Domain – used for package name which uniquely identifies your app in playstore.
  • Package name – reverse domain name, java conventions apply here.
  • Project Location – folder where you want to save your project files.

Next select, Minimum SDK – the minimum Android version that your app is going to run on. For new developments, chose it atleast API level 16.

Next chose an Activity – for this app, we chose it to be Blank or Empty Activity. Follow the next screens and click on Finish. This is going to create and setup your Android project. It may take a little bit of time.

Right click on your project ‘app’  -> click on Open Module Settings (F4) – this shows the project options like the compile sdk version, signing your app, etc.

 

Video 20 : Configuring Android Virtual Device (AVD) – Emulator

Creating virtual device , AVD ,  Emulator , Nexus 5 device

https://www.udemy.com/android-marshmallow-java-app-development-course/learn/v4/t/lecture/3608146

Tools -> Android -> AVD Manager

If you have got an Intel CPU on your machine, click on ‘Use Host GPU’ while creating your virtual device.

HAXM requires 8 GB of RAM or more. If you can’t run HAXM on your machine, then chose ARM EABI v7a System image for your virtual device to run.

 

Video 21 : Run your app on Emulator / AVD

First start your Emulator and let it be running.

https://www.udemy.com/android-marshmallow-java-app-development-course/learn/v4/t/lecture/3608148

Emulator does a pretty good job of showing what your application will look like, But when you are planning to upload your app to play store, you did run your app on physical device.

 

Video 22 : Run your app on Physical device

You need to have a USB cable.
You need to install drivers related to your OEM vendor and configure your Android device so that it can be detected by your computer or laptop.

Install OEM USB drivers

https://www.udemy.com/android-marshmallow-java-app-development-course/learn/v4/t/lecture/3608152

 

2 Android Studio Installation

Video 7 & 8 : Downloading and Installing JDK on Windows

First, we need to install Java JDK on our machine.

Step 1 : For windows installation, check this video :

https://www.udemy.com/android-marshmallow-java-app-development-course/learn/v4/t/lecture/3628530

Video 9 : Install Android Studio on Windows

Step 2 : Installing Android Studio on Windows :

https://www.udemy.com/android-marshmallow-java-app-development-course/learn/v4/t/lecture/3608114

Visit website :

http://www.developer.android.com

Android Studio configuration :

check the instructions video from 6.30 mins.

Video 10 : Configure Android SDK

Step 3: Configuring Android SDK inside Android Studio  *** important step

https://www.udemy.com/android-marshmallow-java-app-development-course/learn/v4/t/lecture/3608120

this is nothing but Configuring Android Development Kit, basically installing different versions of Android platforms…

Video 11, 12 & 13 : Installing Android Studio on MAC and Configuration

Video 14, 15 & 16 : Installing Android Studio on Ubuntu Linux and Configuration

 

Video 19 : Android Studio 2.0 changes :

Project views has changed..

https://www.udemy.com/android-marshmallow-java-app-development-course/learn/v4/t/lecture/4946214

An Empty project created using Android Studio 2.0 includes FAB(Floating Action Button). Remove this from your project if you don’t need.

 

1 Introduction to Marshmallow Development

Udemy Course Link

https://www.udemy.com/android-marshmallow-java-app-development-course/learn/v4/content

Video 1 : Watch Videos in HD for Best Result
Make sure you play videos with the quality of atleast 720p selected.

Video 2 : What is covered in the course

Complete step-by-step guide to developing Android apps using Java. The course is originally developed in October 2014.

You will learn about the best programming tools – Android Studio.

You will learn Java as well, as this is the language we use to develop Android apps.

You develop TEN apps from scratch.

Video 3 : Getting Help when you need it

Go through course discussion for any help. Click on Browse Q & A link.

Video 4 : About Tim Buchalka

Tutor of Udemy Best selling Android course.

Check out his game on Play store : Syncroz

facebook.com/tim.buchalka

twitter.com/timbuchalka

Video 5 : What’s new in Marshmallow Android 6.0

Android 6 works across lot more devices, tablets, wearable devices like watches and even in Cars!

Improved performance – faster, smoother. Now runs, exclusively on ART runtime. Dex code converted to machine instructions at the time of installation, rather than when running an App. So, improved performance. This is ‘Ahead-of-Time compilation’ than traditional Dalvik which uses ‘Just-in-Time compilation’.

Material Design – came out in Lollipop, and enhanced further in Marshmallow. Used for creating stunning new user interfaces.

WebView – this is now an update in the Google playstore instead of being bundled with the SDK.

Video 6 : Just a Few FAQs regarding the course and in general of Android tools and development.

 

Android Services – Part 1

A service is a component that runs in the background to perform long-running operations without needing to interact with the user and it works even if application is destroyed.

Service – an Activity that has no user interface.

Process that runs in the background, use to do some long time consuming tasks like downloading a file, uploading some data to the server or playing some music in the background.

Even if the activity that starts the service is destroyed, the service still runs. So even if the app goes out of context, the service still runs.

—->
A service by itself runs on the main thread. RUNS on MAIN thread. So if you want to do some long time consuming stuff from service, then start an AsyncTask or separate thread for doing this.

Service has its own life cycle. This life cycle is independent of user activity.

2 types of services :

  • local service –> which you can access using startService() -> this internally calls onStartCommand()
  • remote service –> which you can access through bindService() –> ** more on this further.

Lifecycle of a Service

Simple example of a local service :

public class MyServcie extends Service {

 

}

 

 

 

 

 

Parcelable with Intents

Passing Serializable data with Intents :

https://www.udemy.com/the-ultimate-android-tutorial/learn/v4/t/lecture/1470686

class MyData implements Serializable {

String name;
String city;
String email:

}

Then I create an object for this class :

MyData mm = new MyData();
mm.name = name.getText().toString();
mm.city = city.getText().toString();
mm.email = email.getText().toString();

To send this object through an Intent :

Bundle b = new Bundle();
b.putSerializable(“myobject”, mm);
i.putExtras(b);

In other activity, how to use this object ??

Intent ii = getIntent();
Bundle bb = ii.getExtras();

MyData mObj = (MyData)bb.getSerializable(“myobject”);

then we can get all the information from this object.

Differences between Serialization and Parcelable

Parcelable and Serialization are used for marshaling and unmarshaling Java objects.  Differences between the two are often cited around implementation techniques and performance results. From my experience, I have come to identify the following differences in both the approaches:

·         Parcelable is well documented in the Android SDK; serialization on the other hand is available in Java. It is for this very reason that Android developers prefer Parcelable over the Serialization technique.

·         In Parcelable, developers write custom code for marshaling and unmarshaling so it creates less garbage objects in comparison to Serialization. The performance of Parcelable over Serialization dramatically improves (around two times faster), because of this custom implementation.

·         Serialization is a marker interface, which implies the user cannot marshal the data according to their requirements. In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection API. This helps identify the Java objects member and behavior, but also ends up creating a lot of garbage objects. Due to this, the Serialization process is slow in comparison to Parcelable.

Passing Parcelable data with Intents :

https://guides.codepath.com/android/using-parcelable#overview

Parcelable — much lighter and much faster as compared to Serializable.

To allow for your class instances to be sent as a Parcel you must implement the Parcelable interface along with a static field called CREATOR, which itself requires a special constructor, private constructor, in your class.

Step 1 : Class needs to implement Parcelable

class MyData implements Parcelable {

String name;
String city;
int zipcode;

public MyData() {
// Normal actions performed by class, since this is still a normal object!
}

// Step 2 : Implement the methods from the Parcelable interface

@Override
public int describeContents() {

}

// this is the method of importance, here the contents are written to the Parcel
@Override
public void writeToParcel(Parcel dest, int flags) {
}

}

Typically, we don’t do anything in describeContents() method. This is mostly used internally.

Inside, writeToParcel() method we write data to the Parcel. This is how we write :

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(city);
dest.writeInt(zipcode);
}

Step 3: Recover data from Parcelable class

After implementing the ‘Parcelable’ interface methods, we need to create the ‘Parcelable.Creator<T> CREATOR’ constant for our class.

In order to recover data from Parcelable, we need to write another inner class  like this :

    // After implementing the `Parcelable` interface, we need to create the 
    // `Parcelable.Creator<T> CREATOR` constant for our class; 
    // Notice how it has our class specified as its type.  
    public static final Parcelable.Creator<MyData> CREATOR = new Parcelable.Creator<MyData>() {

        // This simply calls our new constructor (typically private) and 
        // passes along the unmarshalled `Parcel`, and then returns the new object!
        @Override
        public MyData createFromParcel(Parcel in) {
            return new MyData(in);
        }

        // We just need to copy this and change the type to match our class.
        @Override
        public MyData[] newArray(int size) {
            return new MyData[size];
        }
    };

Now, to create an object from Parcel, we need to write a parameterized constructor in our class.

    // Using the `in` variable, we can retrieve the values that 
    // we originally wrote into the `Parcel`.  This constructor is usually 
    // private so that only the `CREATOR` field can access.
    private MyParcelable(Parcel in) {
        mData = in.readInt();
        mName = in.readString();
        mInfo = in.readParcelable(MySubParcelable.class.getClassLoader());
    }

Note that the Parcelable interface has two methods defined: int describeContents() and void writeToParcel(Parcel dest, int flags). After implementing the Parcelable interface, we need to create the Parcelable.Creator<MyParcelable> CREATOR constant for our class which requires us to define createFromParcel, newArray.

Fully written Example :

public class MyParcelable implements Parcelable {
    // You can include parcel data types
    String mName;
    String mCity;
    int mZipcode;

    // This is where you write the values you want to save to the `Parcel`.  
    // The `Parcel` class has methods defined to help you save all of your values.  
    // Note that there are only methods defined for simple values, lists, and other Parcelable objects.  
    // You may need to make several classes Parcelable to send the data you want.
    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeString(mName);
        out.writeString(mCity);
        out.writeInt(mZipcode);
    }

    // Using the `in` variable, we can retrieve the values that 
    // we originally wrote into the `Parcel`.  This constructor is usually 
    // private so that only the `CREATOR` field can access.
    private MyParcelable(Parcel in) {
        mName = in.readString();
        mCity = in.readString();
        mZipcode = in.readInt();
    }

    public MyParcelable(String name, String city, int zipCode) {
         mName = name;
         mCity = city;
         mZipcode = zipCode;
    }

    public MyParcelable() {
        // Normal actions performed by class, since this is still a normal object!
    }

    // In the vast majority of cases you can simply return 0 for this.  
    // There are cases where you need to use the constant `CONTENTS_FILE_DESCRIPTOR`
    // But this is out of scope of this tutorial
    @Override
    public int describeContents() {
        return 0;
    }

    // After implementing the `Parcelable` interface, we need to create the 
    // `Parcelable.Creator<MyParcelable> CREATOR` constant for our class; 
    // Notice how it has our class specified as its type.  
    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {

        // This simply calls our new constructor (typically private) and 
        // passes along the unmarshalled `Parcel`, and then returns the new object!
        @Override
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }

        // We just need to copy this and change the type to match our class.
        @Override
        public MyParcelable[] newArray(int size) {
            return new MyParcelable[size];
        }
    };
}

Passing Data Between Intents

We can now pass the parcelable data between activities within an intent:

// somewhere inside an Activity
MyParcelable dataToSend = new MyParcelable(name.getText().toString(), city.getText().toString(), Integer.parseInt(zipcode.getText().toString()));
Bundle b = new Bundle();
b.putParcelable("myobject", dataToSend);
Intent i = new Intent(this, NewActivity.class);
i.putExtras(b);
// i.putExtra("myData", dataToSend); // using the (String name, Parcelable value) overload!
startActivity(i); // dataToSend is now passed to the new Activity

and then access the data in the NewActivity using:

public class NewActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent ii = getIntent();
        Bundle bb = ii.getExtras();
        MyParcelable object = (MyParcelable)bb.getParcelable("myobject");
        // MyParcelable object = (MyParcelable) getIntent().getParcelableExtra("myData");
    }
}

Now we can access the parcelable data from within the launched activity.