Navigation Among Activities Using Android Studio 1.0

Introduction

 
In the previous article, we learned about the View and ViewGroup objects. We learned about Layout and resources as well. In a previous article, we created a hierarchy of View and ViewGroup objects. Now I will develop an activity that shows how to migrate from one activity to another. However, choosing an activity from a new project in Android Studio has already been explained in my previous article.
 
Creating an activity named MainActivity
 
What do we need to do? We need to write the code for making an activity just as in a Layout file named activity_main.xml and use the following procedure:
  • change Relative Layout with Linear Layout
  • Add a Text Field
  • Add String resource
  • Add a button and its listener as well
activity_main.xml
 
This file contains all the attributes of the view elements necessary for making activity. Here we are creating a simple activity that contains only a Text Field (please enter a text) and a button named Send.
 
Here is the code,
  1. // activity_main.xml    
  2.     
  3. <?xml version="1.0" encoding="utf-8"?>    
  4.     
  5. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  6.     xmlns:tools="http://schemas.android.com/tools"    
  7.     android:layout_width="match_parent"    
  8.     android:layout_height="match_parent"    
  9.     android:orientation="horizontal">    
  10.     
  11.     <EditText android:id="@+id/edit_message"    
  12.         android:layout_weight="1"    
  13.         android:layout_width="0dp"    
  14.         android:layout_height="wrap_content"    
  15.         android:hint="@string/edit_message" />    
  16.     <Button    
  17.         android:layout_width="wrap_content"    
  18.         android:layout_height="wrap_content"    
  19.         android:text="@string/button_send"    
  20.         android:onClick="sendMessage"/>    
  21.     
  22. </LinearLayout>   
    It is just an activity with a Text Field and a Button. Now we attach a navigation-among-activities-using-android-studio:onClick attribute so that the message can be sent and another activity will receive that message.  
    String.xml
     
    String.xml contains the string resources such as "app name" , "edit_message" , "action settings" and so on. So we must remove the default string "hello world".
    1. <?xml version="1.0" encoding="utf-8"?>    
    2. <resources>    
    3.     
    4.     <string name="app_name">Megatron</string>    
    5.     <string name="edit_message">please enter a text</string>    
    6.     <string name="button_send">Send</string>    
    7.     <string name="action_settings">Settings</string>    
    8.     <string name="title_activity_main">Main_Activity</string>    
    9.     <string name="title_activity_child">ChildActivity</string>    
    10.         
    11. </resources>   
      It is just an activity with a Text Field with a Button. Now just try to attach a listener of the button so that the message can be sent and another activity will receive that message. 
       
      XML Design
       
      The previous code produces the following output:
       
      design of xml part
       
      Building an Intent
       
      After creation of the first activity with a TextField and a Button as explained above it is now time to initiate this activity using a thing called an Intent.
       
      An Intent is an object that provides runtime binding between two separate components (such as two activities). The Intent represents an application's  "intent to do something". Intents could be used for a wide variety of tasks, but most often they are used to start another activity.
       
      In MainActivity.java declare a method named sendMessage(View view) with these parameters and inside it create an Intent to start an activity called DisplayMessageActivity with this code given below:
      1. public void sendMessage(View view) {    
      2.     Intent intent = new Intent(this, ChildActivity.class);    
      3. }   
      • We need to create a class for ChildActivity because the reference to this class might raise an error in Android Studio.
      • Note that in the constructor used here, "this" is used because the Activity is a subclass of the Context class and imports the Intent class. ( import navigation-among-activities-using-android-studio.content.Intent; ).
         
        However, Android Studio automatically suggests that we press ALT+ENTER and the relevant class will be imported and the packages as well.
      • Inside the sendMessage() method use findViewById() to get an EditText element.
        1. EditText editText = (EditText) findViewById(R.id.edit_message);   
      • At the top of the file import the EditText class again. Press ALT+ENTER and the relevant class will be imported and the packages as well.
      • Assign the text to a local message variable and use the putExtra() method as in the following:
        1.  String message = editText.getText().toString();    
        2.  intent.putExtra(EXTRA_MESSAGE, message);    

      • We must add an EXTRA_MESSAGE definition as shown below:
        1. public class MyActivity extends ActionBarActivity {    
        2.     public final static String EXTRA_MESSAGE = "com.example..megatron.MESSAGE";    
        3.     
        4. }   
      • Finally just finish the sendMessage() method with startActivity(intent) and now invoke the send button.
      MainActivity.java will look such as: 
      1. package com.example.gkumar.megatron;    
      2.     
      3. import android.content.Intent;    
      4. import android.support.v7.app.ActionBarActivity;    
      5. import android.os.Bundle;    
      6. import android.support.v7.internal.widget.AdapterViewCompat;    
      7. import android.view.Menu;    
      8. import android.view.MenuItem;    
      9. import android.view.View;    
      10. import android.widget.EditText;    
      11.     
      12.     
      13. public class Main_Activity extends ActionBarActivity {    
      14.     Public final static String EXTRA_MESSAGE="com.example.gkumar.megatron.MESSAGE"    
      15.     @Override    
      16.     protected void onCreate(Bundle savedInstanceState) {    
      17.         super.onCreate(savedInstanceState);    
      18.         setContentView(R.layout.activity_main_);    
      19.     
      20.     }    
      21.     public void sendMessage(View view)    
      22.     {    
      23.         // building an Intent    
      24.         Intent intent= new Intent(this,ChildActivity.class);    
      25.     
      26.         EditText editText = (EditText) findViewById(R.id.edit_message);    
      27.         String message = editText.getText().toString();    
      28.         intent.putExtra(EXTRA_MESSAGE , message);    
      29.         startActivity(intent);    
      30.     
      31.     }    
      32.     
      33.     @Override    
      34.     public boolean onCreateOptionsMenu(Menu menu) {    
      35.         // Inflate the menu; this adds items to the action bar if it is present.    
      36.         getMenuInflater().inflate(R.menu.menu_main_, menu);    
      37.         return true;    
      38.     }    
      39.     
      40.     @Override    
      41.     public boolean onOptionsItemSelected(MenuItem item) {    
      42.         // Handle action bar item clicks here. The action bar will    
      43.         // automatically handle clicks on the Home/Up button, so long    
      44.         // as you specify a parent activity in AndroidManifest.xml.    
      45.         int id = item.getItemId();    
      46.     
      47.         //noinspection SimplifiableIfStatement    
      48.         if (id == R.id.action_settings) {    
      49.             return true;    
      50.         }    
      51.     
      52.         return super.onOptionsItemSelected(item);    
      53.     }    
      54. }   
        Now the sending and action procedure is completed. Now after clicking the send button a something must be there to catch the text being entered by the user. Then for this we need to create a new Activity.
        Create a second activity
        • Go to the Java directory on the package name com.example.gkumar.megatron. Right-click it and select new > Activity > Blank Activity.
        choosing an activity explicit
        • In the naming window of Activity choose Activity name as ChildActivity
        • layout Name : activity_child.xml
        • Title: ChildActivity
        • Hierarchical parent: MainActivity
        • package name: com.example.gkumar.megatron
        naming this activity blank
         
         
        Click Finish and open the ChildActivity.java file and use the following procedure:
        • The newly created Activity file must have an implementation of onCreate() and onOptionsItemSelected(), that handles the action bar's up behavior and must remain untouched.
           
        • Remove the onCreateOptionsMenu() method, we don't need it.
        Receive the Intent
         
        As we all know and learned above that every activity needs an Intent irrespective of the user's handling of Activity.
        • Look at the default method generated by setContentView(R.layout.activity_display_message). Remove that line.
           
        • Get the intent and assign it to a local variable.
          1. Intent intent = getIntent();   
        • At the top import the Intent class as we did in MainActivity.java.
           
        • Now receive the message delivered by the previous activity using the getStringExtra() method.
          1. String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);   
        Display the Message
        • in the onCreate() method create a TextView object
        • set the text size and message with setText();
           
        • set the text size up to 50 and the text as a message.
           
        • add the TextView as a root view of the activity's layout by ing it to setContentView(textview);
        ChildActivity.java
        1. package com.example.gkumar.megatron;    
        2.     
        3. import android.content.Intent;    
        4. import android.support.v7.app.ActionBarActivity;    
        5. import android.os.Bundle;    
        6. import android.view.Menu;    
        7. import android.view.MenuItem;    
        8. import android.widget.TextView;    
        9.     
        10.     
        11. public class ChildActivity extends ActionBarActivity {    
        12.     
        13.     @Override    
        14.     protected void onCreate(Bundle savedInstanceState) {    
        15.         super.onCreate(savedInstanceState);    
        16.                   // receiving the intent    
        17.         Intent intent = getIntent();    
        18.         String message = intent.getStringExtra(Main_Activity.EXTRA_MESSAGE);    
        19.             
        20.         // display the message    
        21.     
        22.         TextView textview = new TextView(this);    
        23.         textview.setTextSize(50);    
        24.         textview.setText(message);    
        25.     
        26.         // set the text view as the activity layout    
        27.         setContentView(textview);    
        28.     
        29.     }    
        30.     
        31.     
        32.     @Override    
        33.     public boolean onCreateOptionsMenu(Menu menu) {    
        34.         // Inflate the menu; this adds items to the action bar if it is present.    
        35.         getMenuInflater().inflate(R.menu.menu_child, menu);    
        36.         return true;    
        37.     }    
        38.     
        39. }   
         Output
         
        After executing the preceding code I am getting the following errors: 
         
        errors android studio
         
        Although I am working on it I hope the output will be posted very soon.
         

        Summary

         
        In this article, we learned how to migrate from one Activity to another Activity using Intents. In Android, everything on the screen that is user intractable is called an activity. This article explains the entire procedure very clearly. However, it includes nearly three major steps to do as shown, for example creating an activity, building intent and creation another activity for receiving the pushed text.


        Similar Articles