Android Intent example

Have you ever thought how you are navigated from one screen to another in Android application? Here is the answer. Intent – a jargon in Android is doing all the work at background. Go through the post, you will learn how to navigate from one screen to another.

What is Intent?

    • Intents are system messages, running around the inside of the device, notifying applications of various events, from hardware state changes (e.g.,an SD card was inserted), to incoming data (e.g., an SMS message arrived),to application events (e.g., your activity was launched from the device’s main menu).

  • Not only can you respond to intents, but you can create your own, to launch other activities, or to let you know when specific situations arise (e.g., raise such-and-so intent when the user click this button).
  • Intents are asynchronous messages which allow Android components to request functionality from other components of the Android system. For example an Activity can send an Intents to the Android system which starts another Activity.
  • Three of the core components of an application — activities, services, and broadcast receivers — are activated through messages, called intents [Read more at android developers site].

What are we going to develop?

Subscribe and download free ebook
Email:

A simple application which has two screens:

Screen1 contains three controls – TextView shows ‘Enter your name’ text, Edittext to get name from the user and Button to take user to next screen

Screen2 contains only one control – TextView which displays greet message

Quick Links

Project Structure

Layout creation:

  • Create new android project [File >> New >> Android Project] with project name IntentExample
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – com.prgguru.android
  • Click finish

Code Listings

Create layout for Screen 1(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:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enter your name"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
        <requestFocus />
    </EditText>
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take me to next screen" />
</LinearLayout>

Layout for Screen 1 should look like:

Create layout for Screen 2:
Create new layout xml named greeting.xml under /res/layout

<?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"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:text="TEXT"/>
</LinearLayout>

Layout for Screen 2 should look like:

We have to create two java activity classes to handle two screens:

  1.  IntentExampleActivity.java
  2. GreetingActivity.java

1. IntentExampleActivity.java

Create following objects under IntentExampleActivity class:

EditText nameEditCtrl;
Button btnCtlr;
String name;

Refer the controls and set the listener for button inside onCreate method of IntentExampleActivity class:

nameEditCtrl = (EditText) findViewById(R.id.editText1);
btnCtlr = (Button) findViewById(R.id.button1);
btnCtlr.setOnClickListener(new ButtonClickHandler());

Create Button listener class for button1 inside IntentExampleActivity class:

public class ButtonClickHandler implements View.OnClickListener {
//When button is clicked
public void onClick(View view) {
//If name field is not empty, name variable is assigned with entered name
if (nameEditCtrl != null && nameEditCtrl.getText().length() != 0) {
name = nameEditCtrl.getText().toString();
}
//If name is not entered, String 'Guest' is assigned to name variable
else{
name ="Guest";
}
//Create Intent object which moves from IntentExampleActivity class 
//to GreetingActivity class
Intent intObj = new Intent(IntentExampleActivity.this,GreetingActivity.class);
//Set user entered name in value name which will be 
//used in GreetingActivity class
intObj.putExtra("USERNAME", name);
//Start GreetingActivity 
startActivity(intObj);
}
}

2. GreetingActivity.java

Create Java class named ‘GreetingActivity’ under com.prgguru.android package and replace the default skeleton with below one:

package com.prgguru.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class GreetingActivity extends Activity {
	TextView greetMsg;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.greeting);
		greetMsg = (TextView) findViewById(R.id.textView1);
                //Assign the intent that started this activity 
		Intent intename = getIntent();
                //Get the USERNAME passed from IntentExampleActivity
		String uname = (String) intename.getSerializableExtra("USERNAME");
                //Set text for greetMsg TextView 
		greetMsg.setText("Welcome " + uname);
	}

}

Add GreetingActivity in AndroidManifest.xml under application tag:

<activity android:name=".GreetingActivity"
     android:label="@string/app_name" >
</activity>

Demo

We are done with the development, yet to test the application.

Right click on the project >> Run As >> Android Application >>Choose emulator or Android device



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse &amp;gt;&amp;gt; File &amp;gt;&amp;gt; Import.. &amp;gt;&amp;gt; Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

 

Reference:

Android Intent

Suggested posts for further reading

<a href=”http://programmerguru.com/android-tutorial/android-linearlayout-example” target=”_blank”>Android LinearLayout example</a>

<hr width=”100%” />



Author: Android Guru

Share This Post On
  • Rahul

    very nice :)

  • Sushil Yadav

    Hello Sir,

    Have you any sample for facebook in android v4.2.2

  • KOBENA

    I like it

  • http://javatyro.blogspot.in siddhu

    sir good example and can u please post tutorial for refreshing a part of layout without loading entire layout..like jquery,css divisions..

  • Er. Surya Prakash Chamoli

    nice example sir g…

  • sadam

    Very Nice Thanks for the post

  • Ravi

    Also include this: How to configure back button behavior for multiple screen.?
    How to kill a screen when we navigate to other screen so that back button does not take to previous screen?

    • http://programmerguru.com/android-tutorial Android Guru

      Thanks for letting me know Ravi. Will cover those topics in separate post.

    • sushil yadav

      Also Explain PendingIntent because no any separate link about pending Intent that how to use it ?

      • http://programmerguru.com/android-tutorial Android Guru

        I will write post on PendingIntent. Thanks for letting us know.

x
Subscribe and stay in touch!!

Enter your email and stay on top of things:

Your email address will not be published