Android Programming

Android Intent

An Intent with respect to android development is a mechanism for describing operations that need to be performed in an abstract manner.

As a class Intent belongs to android.content package.

package android.content;

It does implement Parcelable and Cloneable.

public class Intent implements Parcelable, Cloneable {}

Creating Intents

Intents can be created by instantiating the android.content.Intent class. Different Parameters can then be passed depending on the reason for the creation of the intent.

public Intent() {}
public Intent(Intent o) {}
public Intent(String action) {}
public Intent(String action, Uri uri) {}
public Intent(Context packageContext, Class<?> cls){}

Example

Intent i = new Intent(MainActivity.this, SecondActivity.class);

Intents have several methods commonly used.

Specifying Intent Actions

For example the getAction() method. This method gets used to get the general action to be performed. This action will then generally specify the way in which the information in the Intent should be interpreted.

public String getAction() {}

The actions can be set using the setAction() method.

public Intent setAction(String action){}

Limiting Intents to Packages

Intents can be limited to packages. We can do this explicitly using the setPackage(). We can then retrieve the package the intent is limited to using the getPackage().

public String getPackage() {}
public Intent setPackage(String packageName){}

Intent Categories

Categories do give out additional detaisl about the action the intent performs. During the resolution of an intent, only activities that provide all the requested categories get used.

Intent categories can be added, retrieved, removed or even checked.

To add an intent category you use the addCategory() method:

public Intent addCategory(String category) {}

We can retrieve a collection or set of categories:

public Set<String> getCategories() {}

We can also check if an intent has a given category:

 public boolean hasCategory(String category) {}

We can also remove intent category:

public void removeCategory(String category) {}

Putting Data To Intents

Let's now get to more common usage of intents. Intents get used alot to transfer data between activities.

We can pack data to intents, then start use them to start an activity and retrieve those data from the target activity.

1.First and foremost we instantiate the intent:

Intent i=new Intent(MainActivity.this, PageOne.class);

where the PageOne.class is the target activity. The first parameter in this case is a Context object while the second parameter target class.

2.Secondly we invoke the putExtra() methods of the Intent object. The intent class has a variations of these putExtra() methods with various parameters. These variations exist so as to enable us transfer various data types via intents. Some of the data types that can be transfered via intents include:

Simple Data Types

These are the simple data types that can be transfered via intent:

Data Type Method
Boolean public Intent putExtra(String name, boolean value)
Byte public Intent putExtra(String name, byte value)
Char public Intent putExtra(String name, char value)
Int public Intent putExtra(String name, int value)
Long public Intent putExtra(String name, long value)
Short public Intent putExtra(String name, short value)
Float public Intent putExtra(String name, float value)
Double public Intent putExtra(String name, float value)
Double public Intent putExtra(String name, double value)
CharSequence public Intent putExtra(String name, CharSequence value)

Parceled Data types

A parceled/parcelable type is a class whose instance can be written to and read from a parcel. A Parcel is final class belonging to android.os package and is a container for data and object references that are sendable through an IBinder. T Here are built in methods for transferring such data:

Data Type Method
Parcelable public Intent putExtra(String name, Parcelable value)
Parcelable[] public Intent putExtra(String name, Parcelable[] value)

Transferring ArrayLists via Intents

These are teh built-in methods for transferring arraylists:

Data Type Method
ArrayList<Parcelable> public Intent putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable>) value
ArrayList<Integer> public Intent putIntegerArrayListExtra(String name, ArrayList<Integer> value)
ArrayList<String> public Intent putStringArrayListExtra(String name, ArrayList<String> value)
ArrayList<CharSequence> public Intent putCharSequenceArrayListExtra(String name, ArrayList<CharSequence> value)

Transferring Arrays via Intents

You can transfer the arrays of our simple data types via intents using the following methods:

column column
Boolean[] public Intent putExtra(String name, boolean[] value)
Byte[] public Intent putExtra(String name, byte[] value)
Char[] public Intent putExtra(String name, char[] value)
Int[] public Intent putExtra(String name, int[] value)
Long[] public Intent putExtra(String name, long[] value)
Float[] public Intent putExtra(String name, float[] value)
Double[] public Intent putExtra(String name, double[] value)
String[] public Intent putExtra(String name, String[] value)
CharSequence[] public Intent putExtra(String name, CharSequence[] value)

Transferring a Bundle via Intent

A Bundle is a data structure which maps strings to Parcelable values. They can also be packed via this method:

Data Type Method
Bundle public Intent putExtra(String name, Bundle value)

Transferring Serialized data via Intent

Serialization is the process of converting in memory objects into a rigid binary representation. This binary form is basically a sequence of bytes that can be passed around then be deserialized back into memory.

This is one of the techniques that can be used to pass around complex objects between activities.

Once we have the serialized class, we can pass it into the below method.

Data Type Method
Serializable public Intent putExtra(String name, Serializable value)

EXAMPLES

Sending Data

Let's say we have two activities: MainActivity.java and PageOne.java. All these two are activities:

Activity Description
MainActivity.java Will contain a button that when we clicked we open the Second Activity(PageOne.java).We then transfer a simple string to that PageOne.java activity
PageOne.java Will contain a textview to display a string it will receive from MainActivity. But first it will need to unpack that data via the key specified in the MainActivity.

So say we do this in a button click:

openBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i=new Intent(MainActivity.this, PageOne.class);
                i.putExtra("MY_KEY","Hello World");
                MainActivity.this.startActivity(i);
            }
        });

So you can see from the above that:

Code Description
Intent i=new Intent(MainActivity.this, PageOne.class); Create an Intent Object with a constructor taking two parameters, a Context object and Class type.
i.putExtra("MY_KEY","Hello World"); Invoke the putExtra() method of the intent class, passing in two parameters: a String key and String value.
MainActivity.this.startActivity(i); Invoke the startActivity() method of the Activity class. We pass the Intent object as a parameter.

Well that will send data to SecondActivity.

Receiving Data

Now we need to receive data from MainActivity and show in a textview:

We can just do this inside the onCreate() method of that activity:

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

        TextView greetingTxt= (TextView) findViewById(R.id.myGreetingTxt);
        greetingTxt.setText(getIntent().getExtras().getString("MY_KEY"));
    }
Code Description
TextView greetingTxt= (TextView) findViewById(R.id.myGreetingTxt); Just references us a TextView that we can use to display our greeting.
greetingTxt.setText(getIntent().getExtras().getString("MY_KEY")); First we retrieve an Intent object from this Activity by calling the getIntent() method. All activities have an Intent object that did start them. Once we have the Intent object we call it's getString() method passing in our key. This gives us a string data from the intent or null if it does exist. We set the data into our setText() method of the TextView.