Book Image

Android 9 Development Cookbook - Third Edition

By : Rick Boyer
Book Image

Android 9 Development Cookbook - Third Edition

By: Rick Boyer

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! With this extensively updated cookbook, you'll find solutions for working with the user interfaces, multitouch gestures, location awareness, web services, and device features such as the phone, camera, and accelerometer. You also get useful steps on packaging your app for the Android Market. Each recipe provides a clear solution and sample code you can use in your project from the outset. Whether you are writing your first app or your hundredth, this is a book that you will come back to time and time again, with its many tips and tricks on the rich features of Android Pie.
Table of Contents (24 chapters)
Title Page
Copyright and Credits
Dedication
About Packt
Contributors
Preface
Index

Returning a result from an activity


Being able to start one activity from another is very useful and commonly used, but there are times when we need to know the result from the called activity. 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"; 
  1. 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);
}
  1. 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();
}
}
  1. 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, indicating we want a result back. 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 use a simple Toast to display the result back to the user.

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? Android will set the result code to RESULT_CANCEL and the intent to null, which would cause our code to throw an exception if we attempt to access the null result.

We made use of the Toast object, which displays a convenient pop-up message 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 non-trivial applications with several activities, this value can be used to identify which Activity is returning a result.

Note

If startActivityForResult() is called with a negative request code, it will behave the same as if we used 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 8, Alerts and Notifications