Monday, 12 August 2013

Android: How can switch between Activities in Android.

                    [ Activity Switching in Android ]

In this Blog Today I will be discussing about switching between one Activity to another and how can send data between these activities.

Before getting into complete Blog I am giving the code sample for handling activities. Lets assume that our new Activity class name is SecondScreenActivity.java

How to open a new Activity  using intent

 An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but most often they’re used to start another activity.
To open new activity following startActivity() method will be used. 

Intent i = new Intent(getApplicationContext(), SecondScreenActivity.class);
startActivity(i);

 Make key value pair and send it to new activity

putExtra() method is used to send parameter. 


i.putExtra("key", "value");
// here Key is 'rkt'
// and value is 'str1'
i.putExtra("rkt", "str1");




Geting parameters at new activity

getStringExtra() method is used to receive parameters on newly created activity

Intent i = getIntent();
i.getStringExtra("key");
// Receiving parameter having key value as 'rkt'
String str2 = i.getStringExtra("rkt");


Add new activity in AndroidManifest.xml

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

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

Now going in detail by taking a sample project

So now we have all the code sample related to activities. In this Blog i have created two XML layouts(activity_main.xml,second.xml) & two Activities(MainActivity.java,SecondScreenActivity.java). The following diagram will give you an idea about the file structure you will be need in this Blog.


   

 Steps to create a new project

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


<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"
    tools:ignore="hardcodedtext" >

    <EditText
        android:id="@+id/AndroidEdt"
        android:layout_width="280dp"
        android:layout_height="25dp"
        android:layout_marginLeft="60dp"
        android:layout_marginTop="150dp"
        android:background="#000000"
        android:hint="Enter Something in The Box"
        android:textColor="#ff00ff" />

    <Button
        android:id="@+id/AndroidBtn"
        android:layout_width="170dp"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="200dp"
        android:layout_height="34dp"
        android:background="#0000FF"
        android:text="Send to next Screen"
        android:textColor="#ffffff" />

</RelativeLayout>

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

package com.example.robi;

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

public class MainActivity extends Activity {

    EditText Edt1;
    Button Btn1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Edt1 = (EditText) findViewById(R.id.AndroidEdt);
        Btn1=(Button)findViewById(R.id.AndroidBtn);
        Btn1.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent i=new Intent(getApplicationContext(),SecondScreenActivity.class);
                String str1=Edt1.getText().toString();
                i.putExtra("rkt",str1);
                startActivity(i);
            }
           
        });
    }

}


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 second.xml. Insert the following code in second.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"
    tools:ignore="hardcodedtext" >

    <TextView
        android:id="@+id/AndroidTxt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:textSize="17sp"
        android:layout_marginTop="90dp"
        android:textColor="#0000FF" />

    <TextView
        android:id="@+id/AndroidTxt3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:textSize="21sp"
        android:layout_marginTop="10dp"
        android:text="You Have Entered......"
        android:textColor="#ff00ff" />

</RelativeLayout>

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

package com.example.robi;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
import android.content.Intent;

public class SecondScreenActivity extends Activity {

TextView Txt1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
        Txt1=(TextView)findViewById(R.id.AndroidTxt2);
        Intent i=getIntent();
        String str2=i.getStringExtra("rkt");
        Txt1.setText(str2);
    }}


 9. Now everything is ready to use and before running your project make sure that you have an entry of new activity name in AndroidManifest.xml file.If not then open you AndroidManifest.xml file and modify the code as I have given below.

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

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.robi.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.example.robi.SecondScreenActivity" >
        </activity>
    </application>

</manifest>

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



                              
                     (Happy Coding Friends)






Please Share this tutorial On:

7 comments:

  1. Gr8 work!! I was lookig for this code and finally got it here!! Thanks for this post.

    ReplyDelete
  2. Thank you Mr.Robi such a nice blog

    ReplyDelete
    Replies
    1. I glad it helps you, always welcome. keep visiting here.

      Delete