Book Image

Android Application Development Cookbook - Second Edition

By : Kyle Mew
Book Image

Android Application Development Cookbook - Second Edition

By: Kyle Mew

Overview of this book

The Android OS has the largest installation base of any operating system in the world; there has never been a better time to learn Android development to write your own applications, or to make your own contributions to the open source community! This “cookbook” will make it easy for you to jump to a topic of interest and get what you need to implement the feature in your own application. If you are new to Android and learn best by “doing,” then this book will provide many topics of interest. Starting with the basics of Android development, we move on to more advanced concepts, and we’ll guide you through common tasks developers struggle to solve. The first few chapters cover the basics including Activities, Layouts, Widgets, and the Menu. From there, we cover fragments and data storage (including SQLite), device sensors, the camera, and GPS. Then we move on more advanced topics such as graphics and animation (including OpenGL), multi-threading with AsyncTask, and Internet functionality with Volley. We’ll also demonstrate Google Maps and Google Cloud Messaging (also known as Push Notifications) using the Google API Library. Finally, we’ll take a look at several online services designed especially for Android development. Take your application big-time with full Internet web services without having to become a server admin by leveraging the power of Backend as a Service (BaaS) providers.
Table of Contents (23 chapters)
Android Application Development Cookbook Second Edition
Credits
Disclaimer
About the Authors
About the Reviewer
www.PacktPub.com
Preface
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