Wednesday 3 July 2013

How to communicate between separate Activities

Hello Friends,
            Welcome you all in the Android tutorial.

Today we are going to learn “How to communicate between separate Activities”?

We have already developed the GUI application for an android device.
That application has First_Name , Last_Name text-field and one send Button.

We are going to use the same GUI application in today’s session. If you have not created the application please refer the following link:-

How to develop a Graphical User Interface ( GUI ) 


In today’s topic we will create another activity which displays the First_Name and Last_Name on the screen, send by the MainActivity of the GUI application.

Let’s start:-

Step 1: Define a function that handles the onClick event of the Button
           
            In MainActvity.java  add the following line :-

   /* sendData handles the onClick event*/
       public void sendData(View view) {

       }

            Must have condition for the function that handles the onClick event are :-
           ·        It must be public
           ·        It must have a void return type
           ·        It must have a View as the only parameter.

           
Step 2: Add the onClick attribute to the Button

            android:onClick=”sendData”

           sendData is the function which responds to the onClick event. Add onClick attribute on <BUTTON> element in activity_main.xml file.

Step 3: Binding of two Activities
           
            Binding of separate components can be achieved by the Intent object.
           “Intent” provides the run-time binding between separate components (for example between two activities).
           
           Syntax:-
                        Intent intent = new Intent (this, DisplayActivity.class);

            Intent constructor here takes two parameter.
             ·     A Context as the first parameter. We are passing this because Activity class is a subclass of Context.
            ·    The Class of the application component to which the system should deliver the Intent.
            We should deliver the Intent to the another activity named as DisplayActivity. 
            We are going to create this activity later.

Step 4: Create a message what you want to pass it to another activity

            We have designed two Text-Fields in our GUI app.
            We will fetch those data and send it to another activity.
            Check the following code:-
            
            Intent intent = new Intent(this, DisplayActivity.class);
     EditText editText = (EditText) findViewById(R.id.first_name);
     String message = editText.getText().toString();
     
     editText = (EditText) findViewById(R.id.last_name);
     message +="__"+editText.getText().toString();

          findViewById() we are using to find the EditText according to id.
           

            Our modified MainActivity.java code will look like as follows:-
        package com.example.firstgui;

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

        public class MainActivity extends Activity {
 
 public final static String EXTRA_MESSAGE = "Message from MainActivity";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 }

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

 /** Called when the user clicks the Send button */
 public void sendData(View view) {
     // Do something in response to button
  Intent intent = new Intent(this, DisplayActivity.class);
     EditText editText = (EditText) findViewById(R.id.first_name);
     String message = editText.getText().toString();
     
     editText = (EditText) findViewById(R.id.last_name);
     message += "__"+editText.getText().toString();
     
     message ="Welcome , "+message;
     intent.putExtra(EXTRA_MESSAGE, message);
     startActivity(intent);
 }
      }


            In EXTRA_MESSAGE we are keeping some constant message.

          Our modified activity_main.xml file will look like as follows:-
 
    

    
    
    
    
    
    


    

Step 5: Create the Second Activity

               Steps to follow :-

            a)  File à New à Other à Android à AndroidActivity
            b)  Select BlankActivity, click Next.
            c)  Select the GUI Project, “FirstGUI”
            d)  Activity name “DisplayActivity”
            e)  Hierarchical Parent , select the MainActivity of the FirsrGUI app
            f)  Click Finish.





Step 6: Receive the Intent
           
            We can get the Intent by calling getIntent() function. We can also retrieve the data contained within it.


Step 7: Display Message

            We are using a TextView widget to show the received message on the Screen.

            Modify the onCreate() of the DisplayActivity.java , as follow :-
 
         protected void onCreate(Bundle savedInstanceState) 
         {
  super.onCreate(savedInstanceState);
  
   // Get the message from the intent
     Intent intent = getIntent();
     String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

     // Create the text view
     TextView textView = new TextView(this);
     textView.setTextSize(40);
     textView.setText(message);

     // Set the text view as the activity layout
     setContentView(textView);
  }

           
           


Clean and Build your Project. Test it with Emulator or Android Device.






Please give your valuable suggestions / comments. Do not forgot to share :)


No comments:

Post a Comment