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.
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.
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>
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
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.
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
[…] my previous article i had explained how to switch between screens. Here i am going to show single list item details in […]
[…] my previous article i had explained how to switch between screens. Here i am going to show single list item details in […]
[…] 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 […]
ravi ..pls answer this qs asap
when i clicke on the sendnxtscreen button den screen ends abruptly
pls help
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.
It is possible added third activity?
how to do that
I really appreciating you for putting this tutorial simple…
Great.!!
Good job ^^
You make awesome tutorials!!! I wish you wrote my textbook for this class I am taking!!!
it help me a lot bro.. thank you..
hey thr . i just wanna know why have u used log.e .. what is it doing
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.
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
you may have forgot to instantiate the SecondScreen in the XML.
Hi – Although everything worked fine,,, but my LogCat didn’t show any the data.
nice working wwell but “how to switch images between activities”
Thanks Man 🙂
the second activity in androidmanifest shold be .SecondScreenActivity
anyway, good tutorial
nice tutorial dude i made my first app with this. thanks :).
I have some problem and I fix with this… (in manifest)
Shouldbe ONE LINE
very nice
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……..
here DashboardActivity is my next activity on that i want to go
you may have forgot to instantiate the DashboardActivity in the XML.
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.
quite helpful for beginners! thanks!
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.
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 🙂
what is Log.e?
Log.e(“n”, inputName.getText()+”.”+ inputEmail.getText());
plzzz help this discribe a sintext.
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.
Actually when i opened firstactivity, onCreate,onCreateOptions, onOptionsItemSelected,onCreateView methods are overriding ,where to put switching new activity codes in these methods..
Put in onCreate()
@Ravi Tamada:disqus ,even after i used codes in oncreate() methods when i runs its shows Application is Stopped
@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….
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)
*how can I do this
One more Good example. 🙂
nice tutorial
nice tutorial
Great page, just one typo: the startActivity() needs to have a lowercase ‘s’ in Opening new Activity
if i want add a value in first activity and i want to send that in the second activity.. then what to do
We have to use putExtra() method on intent. Check these two lines.
nextScreen.putExtra(“name”, inputName.getText().toString());
nextScreen.putExtra(“email”, inputEmail.getText().toString());
My application crashes when i am trying to switch between the activities.
Please Help
Check LogCat for errors.
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();
}
}
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 ?
Which tutorial you are following?
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.
Pls read google maps docs first. My article is very old one.
Hi ravi
Please can u check my code for any error.
I have tried a lot but i can’t find the mistake.
I don’t need the code. Check the LogCat for error.
it’s so helpful for me
thanks..:)
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;
}
}
}
//————————
you should wwrite this line “Intent i = new Intent(MainActivity.this, UIControl.class);” in oncreate or inside onclick of radio button
Thank you very much.God Bless
wow nice tutorial sir
Nice work sir thanks for sharing a such a helpful post with us.
You are welcome:)
Very good manual, thanks!
I tried without using Log.e method….it worked like a charm>>!! then y we r using that ????
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
ThnQ!!
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?
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);
Thanks so much, this tutorial is brilliant! I spent hours on stack overflow getting no where but applying this easy example worked a treat.
You are welcome Christopher.
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.
thank very good article.write a ebook on android to sell online.
nyc ,,i just njyd working this one,,thanks a lot
This was very well written and very useful thank you