Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Android Application Development Cookbook

You're reading from   Android Application Development Cookbook Over 100 recipes to help you solve the most common problems faced by Android Developers today

Arrow left icon
Product type Paperback
Published in Mar 2016
Publisher
ISBN-13 9781785886195
Length 428 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Rick Boyer Rick Boyer
Author Profile Icon Rick Boyer
Rick Boyer
Kyle Mew Kyle Mew
Author Profile Icon Kyle Mew
Kyle Mew
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Activities FREE CHAPTER 2. Layouts 3. Views, Widgets, and Styles 4. Menus 5. Exploring Fragments, AppWidgets, and the System UI 6. Working with Data 7. Alerts and Notifications 8. Using the Touchscreen and Sensors 9. Graphics and Animation 10. A First Look at OpenGL ES 11. Multimedia 12. Telephony, Networks, and the Web 13. Getting Location and Using Geofencing 14. Getting your app ready for the Play Store 15. The Backend as a Service Options Index

Returning a result from an activity

Being able to start one activity from another is all well and good, but we will often need to know how the called activity has fared in its task or even which activity has been called. The startActivityForResult() method provides the solution.

Getting ready

Returning a result from an activity is not very different from the way we just called the activity in the previous recipes. You can either use the project from the previous recipe, or start a new project and call it GettingResults. Either way, once you have a project with two activities and the code needed to call the second activity, you're ready to begin.

How to do it...

There are only a few changes needed to get the results:

  1. First of all, open MainActivity.java and add the following constant to the class:
    public static final String REQUEST_RESULT="REQUEST_RESULT";
  2. Next, change the way the intent is called by modifying the onClickSwitchActivity() method to expect a result:
    public void onClickSwitchActivity(View view) {
        EditText editText = (EditText)findViewById(R.id.editTextData);
        String text = editText.getText().toString();
        Intent intent = new Intent(this, SecondActivity.class);
        intent.putExtra(Intent.EXTRA_TEXT,text);
        startActivityForResult(intent,1);
    }
  3. Then, add this new method to receive the result:
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK) {
            Toast.makeText(this, Integer.toString(data.getIntExtra(REQUEST_RESULT, 0)), Toast.LENGTH_LONG).show();
        }
    }
  4. Finally, modify onClickClose in SecondActivity.java to set the return value as follows:
    public void onClickClose(View view) {
        Intent returnIntent = new Intent();
        returnIntent.putExtra(MainActivity.REQUEST_RESULT,42);
        setResult(RESULT_OK, returnIntent);
        finish();
    }

How it works...

As you can see, getting the results back is relatively straightforward. We just call the intent with startActivityForResult, so it knows that we want a result. We set up the onActivityResult() callback handler to receive the results. Finally, we make sure that the second activity returns a result with setResult() before closing the activity. In this example, we are just setting a result with a static value. We just display what we receive to demonstrate the concept.

It's good practice to check the result code to make sure that the user didn't cancel the action. It's technically an integer, but the system uses it as a boolean value. Check for either RESULT_OK or RESULT_CANCEL and proceed accordingly. In our example, the second activity doesn't have a cancel button, so why bother to check? What if the user hits the back button? The system will set the result code to RESULT_CANCEL and the intent to null, which will cause our code to throw an exception.

We made use of the Toast object, which is a convenient pop-up message that can be used to unobtrusively notify the user. It also functions as a handy method for debugging as it doesn't need a special layout or screen space.

There's more...

Besides the result code, onActivityResults() also includes a Request Code. Are you wondering where that came from? It is simply the integer value that was passed with the startActivityForResult() call, which takes this form:

startActivityForResult(Intent intent, int requestCode);

We didn't check the request code because we knew we had only one result to handle—but in trivial applications with several activities, this value can be used to identify where the request originated.

Tip

If startActivityForResult() is called with a negative request code, it will behave exactly as if it were a call to startActivity()—that is, it will not return a result.

See also

  • To learn more about creating new activity classes, refer to the Switching between activities recipe
  • For more information about Toasts, check out the Making a Toast recipe in Chapter 7, Alerts and Notifications
You have been reading a chapter from
Android Application Development Cookbook - Second Edition
Published in: Mar 2016
Publisher:
ISBN-13: 9781785886195
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime