Main navigation

Android Concept: Working with Intent (Passing Information from one Activity to another)

adsense


In this post we will learn basic building blocks of Android App. Following are fundamental building blocks of Android:

  1. Activities
  2. Services
  3. Broadcast Receivers
  4. Content Providers
  5. Intents
  6. Intent Filters


Most of the programming you can do using C or java but for Android Mobile Application you have to learn some prerequisite concepts. After this post you will be to make any basic android app with multiple activities.
At the end of tutorial we will make an android program where one Activity will call another Activity. So let’s first clear our concepts about building blocks of Android:

  • Activity: Most of the times you would have heard people saying “you have to make 5 activities or 6 acivities”. That means if you want to create 5 display screens then you have to create 5 activities. In simpler terms Activity is nothing but a simple screen. Every screen in an application is an Activity.
  • Service: It is same as Activity, only difference is that it doesn’t have a display screen. So the purpose of Service is to run a code in the background. For Example: A Media Player Application. If you want to run music in the background without any display screen then Service should be used rather than Activity.
  • Broadcast Receivers: A broadcast receiver is an Android component which allows to register for system or application events. All registered receivers for an event will be notified by Android once this event happens.
  • Content Providers: It is a medium through which an Application can share its database with you or an inbuilt application can share its data to a new application. For Example: If we want to browse a phone then we will just ask “Can I browse the phone” so it will give it to us and we can browse the data (accessing the data). So if Content Providers give me permission to do something then only we can do it in an App.
  • Intent: This is a powerful attribute of Android that allows us to send a message from one Activity to another. So it is an abstract description of an operation to be performed. It can be of two types:

    Explicit Intent: It is the one when you call a particular activity i.e we are very specifically telling “I want to call this Activity” then we say it is an Explicit Intent.

    Implicit Intent: Suppose you say I want to open this page. It can be opened in n number of browsers. So we are not explicitly specifying from where to open the page. This is known as Implicit Intent.

  • Intent Filters: Intent Filters are the means through which a component advertises its own capabilities to handle specific job/operations to the android platform. So it basically covers all the features that an Android App support.
  • Now that we have covered all the basic building blocks, let’s make an Android App where data will be transferred from one Activity to another.

    Before going through below code we would suggest you to make a simple Hello World App and run it on your smartphone. You can learn How to Connect, Configure App on Real Android device and Run Hello World program with Android Studio

    So now let’s make a simple App.

    Creating new project

    Please follow following steps:

    1. Open Android Studio and make a new project with name “Android Device” and company domain application.example.com (I used my company domain i.e androidtutorialpoint.com. Similarly you can use yours).
    2. Click Next and choose android version Lollipop. Again Click Next and Choose Blank Activity.
    3. Leave all things remaining same and Click Finish.

    In this App we will play with two activities where we will pass data from one activity (MainActivity) to another (SecondActivity).

    So now you will be able to see two files as MainActivity.java and content_main.xml. Here we will add following code in MainActivity.java:

    MainActivity.java:

    package com.androidtutorialpoint.myapplication;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.Button;
    
    public class MainActivity extends AppCompatActivity {
    
        Button btn;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            btn=(Button)findViewById(R.id.button);
    
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });
    
            btn.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
                    Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                    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);
        }
    }
    
    
    
    

    In the above code we have added a button (btn) that we will click to move to the second activity. To move to the second Activity we will use an Intent. As soon as button is clicked OnClickListener will be implemented and second activity get started. In Intent(MainActivity.this,SecondActivity.class) first argument is the current class and second argument is the class where we need to pass data. Now start second activity using startActivity(intent)

    Make a new file with the name SecondActivity.java in the same folder where MainActivity.java is stored. Add following code in SecondActivity.java:

    SecondActivity.java

    package com.androidtutorialpoint.myapplication;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    /**
     * Created by navneet on 17/4/16.
     */
    public class SecondActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.second);
    
        }
    
    }
    
    

    Above is a very simple code where we have passed R.layout.second in setContentView which implies second.xml will be displayed on screen as soon as SecondActivity called.

    content_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="https://schemas.android.com/apk/res/android"
        xmlns:app="https://schemas.android.com/apk/res-auto"
        xmlns:tools="https://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.androidtutorialpoint.myapplication.MainActivity"
        tools:showIn="@layout/activity_main">
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:id="@+id/button"/>
    </RelativeLayout>
    
    
    

    Make a similar new file as that of content_main.xml in the same place with name second.xml. It will be implemented when SecondActivity called. Add following code in second.xml:

    second.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="https://schemas.android.com/apk/res/android"
        xmlns:app="https://schemas.android.com/apk/res-auto"
        xmlns:tools="https://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.androidtutorialpoint.myapplication.SecondActivity">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Welcome to Second Activity"/>
    
    </RelativeLayout>
    
    

    In the above code we have added a text “Welcome to Second Activity” which will be shown as soon as button will be clicked in First Activity (MainActivity). This display is part of SecondActivity.

    Now comes the most important step. Add Second Activity name in AndroidManifest.xml i.e activity android:name=”.SecondActivity” activity. Code inside AndroidManifest.xml will look like as below:

    AndroidManifest.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest package="com.androidtutorialpoint.myapplication"
              xmlns:android="https://schemas.android.com/apk/res/android">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:theme="@style/AppTheme.NoActionBar">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>
            <activity android:name=".SecondActivity"></activity>
        </application>
    
    </manifest>
    
    
    

    So our App is ready. Now as soon as you run following screen will be displayed. This is part of first activity (MainActivity).

    android_intent

    Now as soon as you click button, following screen will be displayed which is part of second activity (SecondActivity).

    android_intent

    So in this post, we learnt basic building blocks of Android App and how to pass data from one activity to another using Intent.



    What’s Next

    You can see our next tutorial of How to make a basic App. Here You will be able to make an App from scratch without any external help.

    Let us know if you have any doubts or suggestions. Thanks for reading :). Don’t forget to subscribe for latest Android Tutorials. Also do Like our Facebook Page or Add us on Twitter.

    You can download above code by clicking below:


    Android Tutorial Point Download Now


    Reader Interactions

    Comments

    1. I would say this is one of the amazing post I have ever seen.
      This website is really helpful for android community.
      Thanks for publishing this.

    Leave a Reply

    Advertisment ad adsense adlogger