Receiving a Result From an Activity Using Android Studio 1.0

Introduction

 
In previous articles we have learned about activities. An Activity is something that appears on the screen and of course is user intractable through which the user navigates to another activity in a backward direction and forward direction as well.
 
It is not necessary that using an activity we can navigate to the other activity if and only if there is more than one activity within the application.
 
Wanna more about Activity click here.
 

Getting the result from an activity

 
As in the previous articles we created an intent for migrating to another activity from an existing activity. Now instead of using startActivity() we must use startActivityforResult().
 
Let us see an example very common in Android phones or any other phones, like when a user clicks a photo. In the result of photo clicking he wants a result of that clicked image or photo.
 
Let us take another example of a photo editor application in which the user has two choices, the first choice is an existing image from the gallery and the second is  to take a photo and then the user clicks the image and the image must be shown in the editor itself. It sends the result in another Intent object and the activity receives it in the onActivityResult() callback.
 

Start an activity

 
It is not surprising that when we use a simple activity or call startActivity() we an intent object into it. So in this case here we must provide the additional argument to the startActivityForResult() that is an integer. The integer argument is a "request code" that identifies the request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
 
Let us have a look to the code given below:
  1. //static final int PICK_CONTACT_REQUEST = 1;  // The request code    
  2. //...    
  3. static final int PICK_CONTACT_REQUEST = 1;  // The request code    
  4. ...    
  5. private void pickContact() {    
  6.     Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));    
  7.     pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers    
  8.     startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);    
  9. }   
    In the preceding code we have started an activity and ed an intent along with a request that is PICK_CONTACT_REQUEST.
     

    Receive the Result

     
    After we are done with the preceding code, to start an activity for the result there must be something to store or receive the result. It returns the system calls of our activity's onActivityResult() method. It takes three arguments generally.
     
    The request code you ed to startActivityForResult().
     
    A result code is specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the user backed out or the operation is not commited.
     
    An Intent that carries the result data.
     
    Code to pick a contact for receiving the intent.
    1. @Override    
    2. protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
    3.     // Check which request we're responding to    
    4.     if (requestCode == PICK_CONTACT_REQUEST) {    
    5.         // Make sure the request was successful    
    6.         if (resultCode == RESULT_OK) {    
    7.             // The user picked a contact.    
    8.             // The Intent's data Uri identifies which contact was selected.    
    9.     
    10.            // Do something with the contact here (bigger example below)    
    11.        }    
    12.    }    
    13. }   
      The preceding code explains the result of the intent, so in this case we must understand the format of an intent result of what type the output will be. Doing so becomes very easy when the activity returns a result as one of your own activities.
       
      Apps included with the Android platform offer their own APIs that you can count on for specific result data. Let us consider another example to understand this. When a camera application returns the result of a bitmap icon for the “data”.
       
      The following shows how to query the result data to get the phone number from the selected contact:
      1. @Override    
      2. protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
      3.     // Check which request it is     
      4.     if (requestCode == PICK_CONTACT_REQUEST) {    
      5.         // Make sure the request was successful    
      6.         if (resultCode == RESULT_OK) {    
      7.             // Get the URI that points to the selected contact    
      8.             Uri contactUri = data.getData();    
      9.             // We only need the NUMBER column    
      10.             String[] projection = {Phone.NUMBER};    
      11.     
      12.             // Perform the query on the contact to get the NUMBER column    
      13.             // The query() method should be called from a separate thread to avoid blocking    
      14.             // your app's UI thread. (For the sake of simplicity of the sample, this code doesn't do that.)    
      15.             // Consider using CursorLoader to perform the query.    
      16.             Cursor cursor = getContentResolver()    
      17.                     .query(contactUri, projection, nullnullnull);    
      18.             cursor.moveToFirst();    
      19.             // Retrieve the phone number from the NUMBER column    
      20.             int column = cursor.getColumnIndex(Phone.NUMBER);    
      21.             String number = cursor.getString(column);    
      22.             // Do something with the phone number...    
      23.         }    
      24.     }    
      25. }   
      Note: Before Android 2.3, in other words API level 9, performing a query on the contacts, the provider requires READ_CONTACTS permission for security concerns.
       

      Allowing Another Application to Start our Activity

       
      The preceding portion showed how to start another activity from an activity within an application. Now let us see how to start an activity from another application.
       
      To allow other apps to start the activity, you need to add an <intent-filter> element to your manifest file for the corresponding <activity> element.
       
      When the application is installed on the device the system identifies the intent filters on which you are working with and add the information to the system's intents catalog. Though all these are supported by all other application intents as well.
       
      When an app calls startActivity() or startActivityForResult() with an implicit intent, the system finds which activity (or activities) can respond to the intent.
       

      Add an Intent Filter

       
      The system might send a given intent to an activity that has an intent filter that fulfills the needs or criteria that an intent object must have as in the following:  
      • Action 
         
        A string naming the action to perform is usually one of the platform's defined values, such as ACTION_SEND or ACTION_VIEW. Specify this in your intent filter with the <action> element. The value you specify in this element must be the full string name for the action, instead of the API constant (see the examples below). 
         
      • Data
         
        A description of the data associated with the intent.
         
        Specify this in your intent filter with the <data> element. Using one or more attributes in this element, you can specify just the MIME type, just a URI prefix, just a URI scheme, or a combination of these and others that indicate the data type accepted. 
         
      • Category 
         
        It provides an additional way to characterize the activity handling the intent, usually related to the user gesture or location from which it's started. There are several different categories supported by the system, but most are rarely used. However, all implicit intents are defined with CATEGORY_DEFAULT by default.
      In the intent filters we define which criteria your activity accepts by declaring each of them corresponding to the XML elements nested in the <intent-filter> element.
       
      For example: an intent filter that handles the ACTION_SEND intent when the data type is either text or an image and let us analyze the code given: 
      1. <activity android:name="ShareActivity">    
      2.     <intent-filter>    
      3.         <action android:name="android.intent.action.SEND"/>    
      4.         <category android:name="android.intent.category.DEFAULT"/>    
      5.         <data android:mimeType="text/plain"/>    
      6.         <data android:mimeType="image/*"/>    
      7.     </intent-filter>    
      8. </activity>  
      Let us have a look at other code. Here we have defined a filter for sending text and images and on the other hand it receives the intent. 
      1.  <!-- filter for sending text; accepts SENDTO action with sms URI schemes -->    
      2.     <intent-filter>    
      3.         <action android:name="android.intent.action.SENDTO"/>    
      4.         <category android:name="android.intent.category.DEFAULT"/>    
      5.         <data android:scheme="sms" />    
      6.         <data android:scheme="smsto" />    
      7.     </intent-filter>    
      8.     <!-- filter for sending text or images; accepts SEND action and text or image data -->    
      9.     <intent-filter>    
      10.         <action android:name="android.intent.action.SEND"/>    
      11.         <category android:name="android.intent.category.DEFAULT"/>    
      12.         <data android:mimeType="image/*"/>    
      13.         <data android:mimeType="text/plain"/>    
      14.     </intent-filter>    
      15. </activity>   
      Now to receive the implicit intents you must include category_Default in the intent filter.
       

      Handle the Intent in Activity

       
      The following is the completed XML part. Now to receive an intent and the result that it carries. Let us code the remaining Java part that shows only the receiving part of the intent.
      1. @Override    
      2. protected void onCreate(Bundle savedInstanceState) {    
      3.     super.onCreate(savedInstanceState);    
      4.     
      5.     setContentView(R.layout.main);    
      6.     
      7.     // Get the intent that started this activity    
      8.     Intent intent = getIntent();    
      9.     Uri data = intent.getData();    
      10.     
      11.     // Figure out what to do based on the intent type    
      12.     if (intent.getType().indexOf("image/") != -1) {    
      13.         // Handle intents with image data ...    
      14.     } else if (intent.getType().equals("text/plain")) {    
      15.         // Handle intents with text ...    
      16.     }    
      17. }   
      Returning a Result
       
      If we want to take the result from the intent then from the code above, create an intent to deliver the result.
       
      Create the intent so that it can deliver the result.
      1. Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri");    
      2. setResult(Activity.RESULT_OK, result);     
      3. finish();   
        If you simply need to return an integer that indicates one of several result options, you can set the result code to any value higher than 0. If you use the result code to deliver an integer and you have no need to include the Intent, you can call setResult() and only a result code.
         
        For example:
        1. setResult(RESULT_COLOR_RED);    
        2. finish();   
          Note: Simply call the setResult(); method to determine whether an activity has started or not, there is no need to call startActivityForResult().
           

          Summary

           
          This article showed how to start an activity from an activity using another application's activity. Using implicit intents and intent filters we can do this.