In Android user interface is displayed through an activity. In Android app development you might face situations where you need to switch between one Activity (Screen/View) to another. In this tutorial I will be discussing about switching between one Activity to another and sending data between activities.

Download Code

Before getting into complete tutorial I am giving the code snippets for handling activities. Lets assume that our new Activity class name is SecondScreen.java

Opening new Activity

To open new activity following startActivity() or startActivityForResult() method will be used.

Intent i = new Intent(getApplicationContext(), SecondScreen.class);
StartActivity(i);

 

Sending parameters to new Activity

To send parameter to newly created activity putExtra() methos will be used.

i.putExtra("key", "value");

// Example of sending email to next screen as
// Key = 'email'
// value = 'myemail@gmail.com'
i.putExtra("email", "myemail@gmail.com");

 

Receiving parameters on new Activity

To receive parameters on newly created activity getStringExtra() method will be used.

Intent i = getIntent();
i.getStringExtra("key");

// Example of receiving parameter having key value as 'email'
// and storing the value in a variable named myemail
String myemail = i.getStringExtra("email");

 

Opening new Activity and expecting result

In some situations you might expect some data back from newly created activity. In that situations startActivityForResult() method is useful. And once new activity is closed you should you use onActivityResult() method to read the returned result.

Intent i = new Intent(getApplicationContext(), SecondScreen.class);
startActivityForResult(i, 100); // 100 is some code to identify the returning result

// Function to read the result from newly created activity
@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){

             // Storing result in a variable called myvar
             // get("website") 'website' is the key value result data
    	     String mywebsite = data.getExtras().get("result");
        }

    }

 

Sending result back to old activity when StartActivityForResult() is used

Intent i = new Intent();
// Sending param key as 'website' and value as 'androidhive.info'
i.putExtra("website", "AndroidHive.info");

// Setting resultCode to 100 to identify on old activity
setResult(100,in);

 

Closing Activity

To close activity call finish() method

finish();

 

Add entry in AndroidManifest.xml

To run our application you should enter your new activity in AndroidManifest.xml file. Add new activity between <application> tags

<activity android:name=".NewActivityClassName"></activity>

 

Let’s Start with a simple project

So now we have all the code snippets related to activities. In this tutorial i created two xml layouts(screen1.xml, screen2.xml) and two Acvities(FirstScreenActivity.java, SecondScreenActivity.java). The following diagram will give you an idea about the file structure you will be need in this tutorial.

Directory Structure

Now lets start by creating a simple project.

1. Create a new project File -> Android Project. While creating a new project give activity name as FirstScreenActivity.
2. Now you need to create user interface for the FirstScreenActivity.java
3. Create a new xml file in layout folder or rename the main.xml to screen1.xml
Right Click on Layout -> New -> Android XML file and name it as screen1.xml
4. Now insert the following code in screen1.xml to design a small layout. This layout contains simple form with a button.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView android:layout_width="fill_parent"
    		android:layout_height="wrap_content"
    		android:text="Name: "/>
    <EditText android:id="@+id/name"
    		android:layout_width="fill_parent"
    		android:layout_height="wrap_content"
    		android:layout_marginBottom="10dip"/>
    <TextView
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Email: "
	    />
    <EditText android:id="@+id/email"
    		android:layout_width="fill_parent"
    		android:layout_height="wrap_content"
    		android:layout_marginBottom="10dip"/>
    <Button android:id="@+id/btnNextScreen"
     		android:layout_width="fill_parent"
    		android:layout_height="wrap_content"
    		android:text="Send to Next Screen"
    		android:layout_marginTop="15dip"/>
</LinearLayout>

Screen1.xml output

5. Now open your FirstScreenActivity.java and Type the following code. In the following code we are creating a new Intent and passing parameters on clicking button.

package com.example.androidswitchviews;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class FirstScreenActivity extends Activity {
	// Initializing variables
	EditText inputName;
	EditText inputEmail;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen1);

		inputName = (EditText) findViewById(R.id.name);
		inputEmail = (EditText) findViewById(R.id.email);
		Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);

		//Listening to button event
		btnNextScreen.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				//Starting a new Intent
				Intent nextScreen = new Intent(getApplicationContext(), SecondScreenActivity.class);

				//Sending data to another Activity
				nextScreen.putExtra("name", inputName.getText().toString());
				nextScreen.putExtra("email", inputEmail.getText().toString());

				Log.e("n", inputName.getText()+"."+ inputEmail.getText());

				startActivity(nextScreen);

			}
		});
	}
}

6. Create a class called SecondScreenActivity.java. Right Click on src/yourpackagefolder -> New -> Class and name it as SecondScreenActivity.java

Android creating new class

7. Now we need interface for our Second Actvity. Create a new xml file and name it as screen2.xml.
Right Click on Layout -> New -> Android XML file and name it as screen2.xml. Insert the following code in screen2.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <TextView android:layout_width="fill_parent"
  			android:layout_height="wrap_content"
  			android:text="You Entered..."
  			android:textSize="25dip"
  			android:gravity="center"
  			android:layout_margin="15dip"/>

  <TextView android:id="@+id/txtName"
  			android:layout_width="fill_parent"
  			android:layout_height="wrap_content"
  			android:layout_margin="15dip"
  			android:textSize="18dip"/>

  <TextView android:id="@+id/txtEmail"
  			android:layout_width="fill_parent"
  			android:layout_height="wrap_content"
  			android:layout_margin="15dip"
  			android:textSize="18dip"/>

  <Button android:id="@+id/btnClose"
  			android:layout_width="fill_parent"
  			android:layout_height="wrap_content"
  			android:layout_marginTop="15dip"
  			android:text="Close"/>

</LinearLayout>

8. Now open SecondScreenActivity.java and type the following code. Here we are simply reading the parameters and displaying them on to screen

package com.example.androidswitchviews;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SecondScreenActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);

        TextView txtName = (TextView) findViewById(R.id.txtName);
        TextView txtEmail = (TextView) findViewById(R.id.txtEmail);
        Button btnClose = (Button) findViewById(R.id.btnClose);

        Intent i = getIntent();
        // Receiving the Data
        String name = i.getStringExtra("name");
        String email = i.getStringExtra("email");
        Log.e("Second Screen", name + "." + email);

        // Displaying Received data
        txtName.setText(name);
        txtEmail.setText(email);

        // Binding Click event to Button
        btnClose.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				//Closing SecondScreen Activity
				finish();
			}
		});

    }
}

9. Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.androidswitchviews"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FirstScreenActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- Add new Activity class name here --->
        <activity android:name=".SecondScreen"></activity>

    </application>
</manifest>

10. Finally run your project by right clicking on your project folder -> Run As -> 1 Android Application. You can see the application is running by switching between screens. The below image is output screenshots of both xml files.

Switching between views in Android Output
Subscribe
Notify of
guest
230 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] my previous article i had explained how to switch between screens. Here i am going to show single list item details in […]

trackback

[…] my previous article i had explained how to switch between screens. Here i am going to show single list item details in […]

trackback

[…] i had 6 icons on my dashboard, so i need 6 Activities one for each icon. In my previous article How to switch between Activities in Android i explained switching between […]

varun
varun
7 years ago

ravi ..pls answer this qs asap

when i clicke on the sendnxtscreen button den screen ends abruptly
pls help

Ravi
Ravi
7 years ago

Thanks a lot Ravi. Please keep going such tutorials.

your explanation is awesome. I am a newbie but able to understand yours explanation. Thanks a lot.

Alex
Alex
7 years ago

It is possible added third activity?

sumanth
sumanth
7 years ago

how to do that

Prathap
Prathap
7 years ago

I really appreciating you for putting this tutorial simple…

prasini.fotia
prasini.fotia
7 years ago

Great.!!

manggala
manggala
7 years ago

Good job ^^

Wondernate
Wondernate
7 years ago

You make awesome tutorials!!! I wish you wrote my textbook for this class I am taking!!!

avinash
avinash
7 years ago

it help me a lot bro.. thank you..

Saman
Saman
7 years ago

hey thr . i just wanna know why have u used log.e .. what is it doing

George
George
7 years ago

Awsome tutorials. Finally someone who learns others not forgetting the “K.I.S.S.” principle.
Thanks alot for the time spent on making the tutorials and website.

Jerome Laniog
Jerome Laniog
7 years ago

I removed the input part of this and I know it wont affect the process because I only want to go to the next screen by clicking the button. There are no errors but when I get to the emulator, the app crashes after I clicked the button. Please help T.T

Z.A Khan
Z.A Khan
6 years ago
Reply to  Jerome Laniog

you may have forgot to instantiate the SecondScreen in the XML.

Junaid Ali
Junaid Ali
7 years ago

Hi – Although everything worked fine,,, but my LogCat didn’t show any the data.

siddhu
siddhu
7 years ago

nice working wwell but “how to switch images between activities”

Milinko Dragovic
Milinko Dragovic
7 years ago

Thanks Man 🙂

Reinhard Panuturi Siringoringo
Reinhard Panuturi Siringoringo
7 years ago

the second activity in androidmanifest shold be .SecondScreenActivity
anyway, good tutorial

ps
ps
6 years ago

nice tutorial dude i made my first app with this. thanks :).

Kastam RO
Kastam RO
6 years ago

I have some problem and I fix with this… (in manifest)

Shouldbe ONE LINE

Seyed Ahmad Parkhid
Seyed Ahmad Parkhid
6 years ago

very nice

friend
friend
6 years ago

Thank you
I have some problem on clicking the button that gives an error that:::
” E/AndroidRuntime(884): FATAL EXCEPTION: main” and
” E/AndroidRuntime(884): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sari/com.example.sari.DashboardActivity}: java.lang.NullPointerException”

please give me such solution but which i can go to my next screen by clicking on Button

please reply me as soon as possible……..

friend
friend
6 years ago
Reply to  friend

here DashboardActivity is my next activity on that i want to go

Z.A Khan
Z.A Khan
6 years ago
Reply to  friend

you may have forgot to instantiate the DashboardActivity in the XML.

george
george
6 years ago

Hello. I need someone
to develop a simple app. will use java , php and sql. please reply to george.celsie@gmail.com
if you can help me. I will share the
credits :). Thanks.

Rakhi Dhavale
6 years ago

quite helpful for beginners! thanks!

Fin
Fin
6 years ago

You’re a very good teacher, you just show what a learner need to know regarding the topic. Straight to the point and clear simple example. Keep up the good work man..very nice.

Nazia
Nazia
6 years ago

It worked fine for me even though i got some Fatal exceptions.
Thanks a lot for such a detailed information.
It helped me a lot 🙂

darshan
darshan
6 years ago

what is Log.e?

darshan
darshan
6 years ago

Log.e(“n”, inputName.getText()+”.”+ inputEmail.getText());
plzzz help this discribe a sintext.

Ravi Tamada
6 years ago
Reply to  darshan

It is print something in console like System.out.println. In Eclipse goto Window -> show view -> Other -> Android -> Log cat. Then you can see the text printing.

PAVAN KUMAR P
PAVAN KUMAR P
6 years ago

Actually when i opened firstactivity, onCreate,onCreateOptions, onOptionsItemSelected,onCreateView methods are overriding ,where to put switching new activity codes in these methods..

Ravi Tamada
6 years ago
Reply to  PAVAN KUMAR P

Put in onCreate()

pavan kumar p
pavan kumar p
6 years ago
Reply to  PAVAN KUMAR P

:disqus ,even after i used codes in oncreate() methods when i runs its shows Application is Stopped

Jordani Rozon
Jordani Rozon
5 years ago
Reply to  PAVAN KUMAR P

@pavankumarp:disqus if you see in the android life cycle, there’s different kind of methods, first thing that android see when you execute it, is the onCreateMethod(), then existe onStart, onDestroy….

XGirliciousX
XGirliciousX
5 years ago

how can I this with swiping motions? I want to swipe to the left but I don’t know how to do it. Please help me. I have a headache now because of programming xD (I am a Media Informatic student)

XGirliciousX
XGirliciousX
5 years ago
Reply to  XGirliciousX

*how can I do this

itechaleart
5 years ago

One more Good example. 🙂

shubham
shubham
5 years ago

nice tutorial

विनय सोमवंशी
विनय सोमवंशी
5 years ago

nice tutorial

Kurt Wilson
Kurt Wilson
5 years ago

Great page, just one typo: the startActivity() needs to have a lowercase ‘s’ in Opening new Activity

irfan
irfan
5 years ago

if i want add a value in first activity and i want to send that in the second activity.. then what to do

Ravi Tamada
5 years ago
Reply to  irfan

We have to use putExtra() method on intent. Check these two lines.

nextScreen.putExtra(“name”, inputName.getText().toString());

nextScreen.putExtra(“email”, inputEmail.getText().toString());

Govind
Govind
5 years ago

My application crashes when i am trying to switch between the activities.
Please Help

Ravi Tamada
5 years ago
Reply to  Govind

Check LogCat for errors.

Govind
Govind
5 years ago
Reply to  Ravi Tamada

package info.androidhive.loginandregistration;

import info.androidhive.loginandregistration.helper.SQLiteHandler;
import info.androidhive.loginandregistration.helper.SessionManager;

import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {

private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
public Button btnnear;

private SQLiteHandler db;
private SessionManager session;

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

txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnnear = (Button) findViewById(R.id.btnnear);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());

// session manager
session = new SessionManager(getApplicationContext());

if (!session.isLoggedIn()) {
logoutUser();
}

// Fetching user details from sqlite
HashMap user = db.getUserDetails();

String name = user.get(“name”);
String email = user.get(“email”);

// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);

// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
logoutUser();
}
});

btnnear.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
//Starting a new Intent
Intent nextScreen = new Intent(MainActivity.this, Nearby.class);
startActivity(nextScreen);

}
});
}

private void logoutUser() {
session.setLogin(false);

db.deleteUsers();

// Launching the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}

Govind
Govind
5 years ago
Reply to  Govind

Hi ravi
Finally prob solved.
But ravi i m not able to access my api key
Its showing an error
Places error
Access deneid.
What should i do ?

Ravi Tamada
5 years ago
Reply to  Govind

Which tutorial you are following?

Govind
Govind
5 years ago
Reply to  Ravi Tamada

Hi ravi .
I have followed almost all ur tutorial and i would like to thank u because all of ur tutorial are very helpful.right now i am using ur google maps and places tutorial .
When i am using ur api key its working but when i trying to use mine i am not able to use it .
I have followed the steps correctly still i am not able to use it.

Ravi Tamada
5 years ago
Reply to  Govind

Pls read google maps docs first. My article is very old one.

Govind
Govind
5 years ago
Reply to  Ravi Tamada

Hi ravi
Please can u check my code for any error.

I have tried a lot but i can’t find the mistake.

Ravi Tamada
5 years ago
Reply to  Govind

I don’t need the code. Check the LogCat for error.

baldha chirag
baldha chirag
5 years ago

it’s so helpful for me

thanks..:)

Vipul Swamy Ballupet
Vipul Swamy Ballupet
4 years ago

hi Ravi, I am using 2 radio buttons, if one of them is clicked i want the app to redirected to a respective activity. although i have included everything in the manifest, it is not loading activity when clicked, a little help will be appreciated…. here is the main activity.

//———————————-

package com.example.lite;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Toast;

public class MainActivity extends Activity {

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

Intent j = new Intent(MainActivity.this, GestureControl.class);

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}

// this method is called at button click because we assigned the name to the

// “OnClick” property of the button

public void onClick(View view) {

switch (view.getId()) {

case R.id.radioButton1:

// Starts TargetActivity

startActivity(i);

Toast.makeText(MainActivity.this, “PAM” , Toast.LENGTH_SHORT).show();

case R.id.radioButton2:

// Starts TargetActivity

startActivity(j);

Toast.makeText(MainActivity.this, “An”, Toast.LENGTH_SHORT).show();

break;

}

}

}

//————————

రామకృష్ణ శర్మ
రామకృష్ణ శర్మ
3 years ago

you should wwrite this line “Intent i = new Intent(MainActivity.this, UIControl.class);” in oncreate or inside onclick of radio button

Vipul Swamy Ballupet
Vipul Swamy Ballupet
3 years ago

Thank you very much.God Bless

Venkatesh Nani
Venkatesh Nani
4 years ago

wow nice tutorial sir

Yash Saradva
4 years ago

Nice work sir thanks for sharing a such a helpful post with us.

Ravi Tamada
4 years ago
Reply to  Yash Saradva

You are welcome:)

Joe
Joe
4 years ago

Very good manual, thanks!

Hn Rakesh
Hn Rakesh
3 years ago

I tried without using Log.e method….it worked like a charm>>!! then y we r using that ????

Ravi Tamada
3 years ago
Reply to  Hn Rakesh

Log.e() is debugging purpose. If you want to print some data in log but not a part of android app, we use Log statements. Go through this
https://developer.android.com/studio/debug/am-logcat.html

Hn Rakesh
Hn Rakesh
3 years ago
Reply to  Ravi Tamada

ThnQ!!

ManHunter
ManHunter
3 years ago

hii Ravi i’m building a BLE Android Application which is showing a Data of sensor or device. now i want integrate to IBM Bluemix cloud. when we will connect to the device from application the data will show on IBM bluemix so can you help me how i’ll connect Android application on bluemix and show the data on bluemix?

jtaco263
jtaco263
2 years ago

Volley not calling getParams() for second time it is not sending the parameters again how do i solve this i saw this code but how to implemente to checklogin() ?

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.getCache().clear();
requestQueue.add(stringRequest);

Christopher Rodwell
Christopher Rodwell
2 years ago

Thanks so much, this tutorial is brilliant! I spent hours on stack overflow getting no where but applying this easy example worked a treat.

Ravi Tamada
2 years ago

You are welcome Christopher.

Paweł Gawędzki
Paweł Gawędzki
2 years ago

Thank you Ravi. I just started my adventure with Android. What I want to do is display one activity (screen) when application settings are not set and second screen when settings are set. The second use case is I want to go from second screen to the first screen whenever I want to change my settings. Thanks to your tutorial my life is easier. So again good job.

webtutor
9 years ago

thank very good article.write a ebook on android to sell online.

Amit hooda
Amit hooda
9 years ago

nyc ,,i just njyd working this one,,thanks a lot

Jnhagerm
Jnhagerm
9 years ago

This was very well written and very useful thank you

230
0
Would love your thoughts, please comment.x
()
x