Thursday, January 15, 2015

How to start another activity from an activity in Android

Start Another Activity
To create this example we uses Android Studio IDE. The following android example code demonstrate us how can we start another Activity from an Activity. Activity is an Android application component that render a screen with which app users can interact to do some task such as sending or reading an email, take a photo by phone camera, navigating through a map etc. Activity generated window typically fill the full screen but it may be smaller and can be float on top of other windows.

Generally an android app consists multiple Activities. Such as an email app have one activity to send email, another activity to read email etc. So, an activity should contact other activities. Typically Activities are bound to each other. In the Activity stack, one Activity are defined as a main Activity which presented to app user when they launch the app at first time. Each Activity can then start another Activity to perform additional task. When a new Activity start, the previous Activity is stopped but Android system preserve the Activity in a stack (Back Stack). When a new Activity starts its pushed on to the back stack and got user focus.

When a new Activity is start Android system stopped the previous Activity. When an Activity stopped, the specified Activity release any large objects such as network or database connection. When the Activity resume it reacquire the necessary resources and resume specified actions.



To create an Activity, app developer must create a subclass of Activity or an existing subclass of it. Android system call onCreate() method when creating an Activity. Within this method we should initialize the essential components of this Activity. The setContentView() method allow us to define the XML layout for the Activity's user interface.

We can start another activity from an Activity by calling startActivity() method. We just need to pass an Intent that describe the new Activity which we want to start. The Intent can specify either the exact Activity or describe the type of action we want to perform (in this situation Android system selects the appropriate Activity, which can even be from a different application). Intent also can carry (pass) small amount of data to the new Activity.

We can start an Activity within same application by using class name. Intent putExtra() method add extended data to the Intent.

An Intent is a messaging object that Android developer can use to request an action from another app component. An Intent used to start an Activity, to start a Service and to deliver a Broadcast. There are two types of Intents, those are Explicit Intents and Implicit Intents. Explicit Intents specify the component to start by name (fully-qualified class name). Typically Explicit Intents are used to start a component within same app. Implicit Intents do not name a specific component but instead declare a general action to perform such as play a video.
The activity_main.xml is our application's main Activity (launcher Activity.) When app users start the app at first time, they see this XML layout file's defined elements in app window. In this Activity we just ask user's City name.
activity_main.xml

<LinearLayout
    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"
    android:orientation="vertical"
    android:layout_gravity="left"
    android:padding="15dp"
    tools:context=".MainActivity"
    >
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Input your city name......"
        android:textSize="25dp"
        />

    <Button
        android:id ="@+id/push_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit your city"
        android:padding="15dp"
        android:textSize="25dp"
        android:onClick="perform_action"
        />
</LinearLayout>
The MainActivity.java file is the java code which manage the main Activity's elements. When app user input a City name in the Main Activity user interface then the java file call the startActivity() method to start another activity to show the user submitted City name. This main Activity also pass the user submitted City name when starting another Activity.
MainActivity.java

package com.cfsuman.me.myapplication5;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

//import additional classes
import android.view.View;
import android.content.Intent;
import android.widget.EditText;


public class MainActivity extends ActionBarActivity {

    //define MESSAGE_TO_PASS String
    public final static String MESSAGE_TO_PASS="com.cfsuman.me.myapplication5.MESSAGE";

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

    public void perform_action(View v)
    {
        //initializing a new Intent
        Intent intent = new Intent(this,DisplayCityActivity.class);

        //reference the EditText widget from layout
        EditText editText = (EditText) findViewById(R.id.edit_text);
        //get user inputted city name
        String city = editText.getText().toString();

        //pass the city name to another activity
        // Intent can carry data types as key-value pairs called Extras
        intent.putExtra(MESSAGE_TO_PASS, city);

        //start the another activity
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
The activity_display_city.xml layout file is the Activity which we want to start from main Activity. This activity just display the app user submitted City name which we get from Intent passed data.
activity_display_city.xml

<LinearLayout
    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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.cfsuman.me.myapplication5.DisplayCityActivity"
    >
    <!--no widget exists to display-->
    <!--we will create widget programmatically  to display-->
</LinearLayout>
The DisplayCityActivity.java file allow us to process the intent passed data and display user submitted City name to XML layout file's corresponded user interface.
DisplayCityActivity.java

package com.cfsuman.me.myapplication5;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

//additional imported classes
import android.content.Intent;
import android.widget.TextView;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.TypedValue;


public class DisplayCityActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //make comment the following line
        //setContentView(R.layout.activity_display_city);

        //get the Intent and assign it to a local variable
        Intent receivedIntent = getIntent();

        //extract the city name from previous activity
        //store the received city name to a variable
        String receivedCity = receivedIntent.getStringExtra(MainActivity.MESSAGE_TO_PASS);

        //create a new TextView object
        TextView tv = new TextView(this);
        tv.setText("Your submitted city is: ");
        //append city name with TextView static text
        tv.append(receivedCity);
        //set the textview text font monospace and style bold italic
        tv.setTypeface(Typeface.MONOSPACE,Typeface.BOLD_ITALIC);
        //set the textview text size 30dip
        tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,30);
        //set the textview text color
        tv.setTextColor(Color.RED);

        //set the new activity content to newly created textview
        setContentView(tv);
    }


    //make comment the following code section
    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_display_city, menu);
        return true;
    }*/

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
The AndroidManifest.xml files hold the both Activities declaration such as Activity name, label, intent filters, meta data etc.
manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cfsuman.me.myapplication5" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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=".DisplayCityActivity"
            android:label="@string/title_activity_display_city"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.cfsuman.me.myapplication5.MainActivity" />
        </activity>
    </application>

</manifest>
res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Android Code Snippets</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_display_city">DisplayCityActivity</string>
</resources>
The following images shows the app in action. This images clearly display how we can start another Activity from an Activity. Main Activity collect the user City and we display it another Activity's user interface.

More android examples