Monday, March 18, 2013

Returning Result from Activity

In  Android an Activity can be started for some results, means an Activity can return some result to the Parent/Previous Activity.

An Activity can return String, Int, float, boolean  etc as Result.

In this post I have two Activities MainActivity   and SecondActivity.
Second Activty returns a String to the First  MainActivity as Result.
From MainActivity we start the Second Activity to get Result with follwing method

startActivityForResult(Intent  intent, int requestCode);


to get the Result back  we need to override the method..

 onActivityResult(int requestCode, int resultCode, Intent data)


the data object (last parameter of above method) contains the returned Result, we need to fetch the result from data(object of Intent).

See the Execution Flow

First Screen:   Click on get Message    (MainActivity)






Second Screen:   Enter the Message " I am much  Busy"   and click on Submit Message  (Second Activity)





3rd Screen :  See the returned message      MainActivity   , you can see the result is being returned to Previous Activity i.e. MainActivity (Which have started the activity for result)






Code:


activtymain.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:gravity="center_vertical"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textViewMessage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textColor="#FF0000"
        android:textSize="20dp"
        android:text="Message" />

    <Button
        android:id="@+id/button1"
        android:layout_marginTop="20dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="Get Message"
        android:onClick="getMessage" />

</LinearLayout>

layout2.xml   



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="vertical" >

  
   
    <EditText
        android:id="@+id/editTextMessage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textColor="#FF0000"
        android:textSize="20sp"
        android:hint="Enter The Message" />

    <Button
      
        android:layout_marginTop="20dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="Submit Message"
        android:onClick="submitMessage" />

</LinearLayout>


MainActivity.java


public class MainActivity extends Activity
{
    TextView  textViewMessage;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // get The refference of The textView
        textViewMessage=(TextView)findViewById(R.id.textViewMessage);
    }

   
    // Method to handle the Click Event on GetMessage Button
    public void getMessage(View V)
    {
            // Create The  Intent and Start The Activity to get The message
            Intent intentGetMessage=new Intent(this,SecondActivity.class);
            startActivityForResult(intentGetMessage, 2);// Activity is started with requestCode 2
    }
   
   
    // Call Back method  to get the Message form other Activity    override the method
    @Override
       protected void onActivityResult(int requestCode, int resultCode, Intent data)
       {
                 // TODO Auto-generated method stub
                 super.onActivityResult(requestCode, resultCode, data);
                
   
                  // check if the request code is same as what is passed  here it is 2
                   if(requestCode==2)
                         {
                            // fetch the message String
                             String message=data.getStringExtra("MESSAGE");
                             // Set the message string in textView
                             textViewMessage.setText(message);
              
                         }
              
     }

}

SecondActivity.java



public class SecondActivity extends Activity
{
    EditText  editTextMessage;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout2);
        // Get the Refference of Edit Text
        editTextMessage=(EditText)findViewById(R.id.editTextMessage);
    }

   
   
    public void submitMessage(View V)
    {
       
        // get the Entered  message
        String message=editTextMessage.getText().toString();
        Intent intentMessage=new Intent();
       
       
        // put the message to return as result in Intent
        intentMessage.putExtra("MESSAGE",message);
        // Set The Result in Intent
        setResult(2,intentMessage);
        // finish The activity
        finish();
       
    }
   
 }


More Android Topics

Android : Introduction


       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app


         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


       Activity

                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android

    ListView:

               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android

      TelephonyManager

                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States In Android

    Miscellaneous

                   Notifications In Android
                   How To Vibrate The Android Phone
                   Sending Email In Android
                  Opening a webpage In Browser
                   How to Access PhoneBook In Android
                   Prompt User Input with an AlertDialog

   Storage:  Storing Data In Android


               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 
                         

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android




12 comments:

  1. having a 'Submit' button on activity is not a good design in general.
    most activities exit with press of back button or navigation bar arrow. Obviously this solution does not cover any of these cases.

    ReplyDelete
  2. I enjoy you bеcɑսse of all ʏour valuable effort on thіs website.
    Ellie enjoys carrying out investigations аnd it'ѕ reɑlly easy to understand why.

    We learn alⅼ cօncerning the lively meɑns you offer useful solutions
    ѵia the blog and welcome participation fгom website visitors аbout this matter ᴡhile ouг princess is
    ᴡithout a doubt learning ɑ ɡreat deal.
    Take advantage of the rest of tһe new year. You are doing a splendid job.

    ReplyDelete
  3. Sߋme truly great articles on this website, appгeciate
    іt for contribution.

    ReplyDelete
  4. I visited multiple blogs but the audio quality for audio songs present
    at this website is genuinely wonderful.

    ReplyDelete
  5. 37 da Constituição Federalista (DI PIETRO, 2007, p. 689).

    ReplyDelete
  6. Curso de direito tributário brasílio,6.

    ReplyDelete
  7. Recta Tributário.11. ed. São Paulo: Atlas ,1999.

    ReplyDelete
  8. Greetings from Los angeles! I'm bored tο death at work ѕo I decided to check ⲟut youг website оn my iphone dսrіng lunch break.
    Ӏ enjoy tһe info yⲟu provide herе and can't wait tο take a look whеn I
    get home. I'm amazed at hoᴡ fast your blog loaded ᧐n my phone ..

    I'm not eᴠen սsing WIFI, just 3G .. Anyways, excellent site!

    ReplyDelete
  9. Nice post. I was checking continuously this blolg and I'm impressed!

    Very helpful info specifically the last part :) I cre for such information a lot.
    I was seeking this certain info for a longg time.
    Thank you and best of luck.

    ReplyDelete
  10. bookmarked!!, I really like your website!

    ReplyDelete
  11. Oh Just the course Have been wanting to Takeon

    ReplyDelete