Android uses startActivityForResult to return data to the previous Activity

  • 2021-12-11 08:57:04
  • OfStack

In Android, jump from one Activity to another Activity, and then return. The first Activity can save data and state by default. But this time I want to achieve the same goal by using startActivityForResult. Although it seems complicated, I can explore the principle behind startActivityForResult and the precautions for using it.

The functions to be implemented are as follows:

Data is passed from Activity A to Activity B, then obtained from Activity B, and then returned to Activity A. Add an Button "back to the previous page" to Activity B. After returning to Activity A, we need to keep the relevant information entered before. We use startActivityForResult to pull up Activity B, so that Activity A will have one waiting for Activity B to return.

The specific steps are as follows:

There is one Button in Activity A. After clicking Button, get the data to be transmitted to Activity B, encapsulate the data into Bundle, and then call startActivityForResult to transmit the data to Activity B Activity A rewrites the onActivityResult function to determine whether requestCode and resultCode are our expected results. If so, the data is retrieved from Bundle and redisplayed in Activity A Obtain the Intent object transmitted by Activity A in Activity B, take out the Bundle object, take out the data field from Bundle, and display it on the current page There is also an Button in Activity B. After clicking Button, call setResult to return the result and close the current page. So, it seems that the effect is to go back to Activity A

The source code is as follows:

1. Implementation of Activity A:


public class ExampleActivity extends Activity {

 private EditText mEditText;
 private RadioButton mRb1;
 private RadioButton mRb2;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main_page_layout);

 Button button = findViewById(R.id.buttonGoToLayout2);
 button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  mEditText = findViewById(R.id.editText);
  //  Get the height you entered 
  double height = Double.parseDouble(mEditText.getText().toString());

  //  Acquisition of gender 
  String gender = "";
  mRb1 = findViewById(R.id.radioButtonMale);
  mRb2 = findViewById(R.id.radioButtonFemale);
  if (mRb1.isChecked()) {
   gender = "M";
  } else {
   gender = "F";
  }

  Intent intent = new Intent(ExampleActivity.this, SecondActivity.class);
  //  Pass data into the 2 A Activity
  Bundle bundle = new Bundle();
  bundle.putDouble("height", height);
  bundle.putString("gender", gender);
  intent.putExtras(bundle);

  startActivityForResult(intent, 0);
  }
 });
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);
 if (resultCode == RESULT_OK && requestCode == 0) {
  Bundle bundle = data.getExtras();
  double height = bundle.getDouble("height");
  String gender = bundle.getString("gender");

  mEditText.setText("" + height);
  if (gender.equals("M")) {
  mRb1.setChecked(true);
  } else {
  mRb2.setChecked(true);
  }
 }
 }
}

2. Layout file main_page_layout. xml:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_gravity="center">

 <TextView
  android:id="@+id/textView1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text=" Calculate standard weight "
  android:paddingTop="20dp"
  android:paddingLeft="20dp"
  android:textSize="30sp"/>

 <TextView
  android:text=" Gender :"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:id="@+id/textView3"
  android:layout_alignStart="@id/textView1" android:layout_marginTop="38dp"
  android:layout_below="@id/textView1" android:layout_marginStart="46dp"/>

 <TextView
  android:text=" Height :"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:id="@+id/textView4"
  android:layout_alignStart="@id/textView1" android:layout_marginStart="46dp"
  android:layout_below="@id/textView3" android:layout_marginTop="29dp"/>

 <EditText android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:id="@+id/editText"
  android:layout_toEndOf="@id/textView4"
  android:layout_marginStart="36dp"
  android:autofillHints="@string/app_name"
  android:hint="0"
  android:layout_alignBaseline="@id/textView4"/>

 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:text=" Centimeters "
  android:layout_alignBaseline="@id/editText"
  android:layout_toRightOf="@id/editText"
  android:layout_marginStart="10dp" />

 <RadioButton
  android:layout_below="@id/textView1"
  android:id="@+id/radioButtonMale"
  android:text=" Male "
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignStart="@id/textView1" android:layout_marginTop="30dp"
  android:layout_marginStart="113dp"/>

 <RadioButton
  android:id="@+id/radioButtonFemale"
  android:text=" Female "
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_below="@id/textView1"
  android:layout_toEndOf="@id/radioButtonMale"
  android:layout_marginLeft="15dp" android:layout_marginTop="30dp" android:layout_marginStart="49dp"/>

 <Button
  android:text=" Calculation "
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/buttonGoToLayout2"
  android:layout_marginTop="90dp"
  android:layout_below="@id/radioButtonMale"
  android:layout_alignStart="@id/textView1" android:layout_marginStart="92dp"/>
</RelativeLayout>

3. Implementation of Activity B:


public class SecondActivity extends Activity {
 private Intent mIntent;
 private Bundle mBundle;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.second_layout);

 mIntent = getIntent();
 mBundle = mIntent.getExtras();

 //  Remember to judge empty 
 if (mBundle == null) {
  return;
 }

 //  Get Bundle Data in 
 double height = mBundle.getDouble("height");
 String gender = mBundle.getString("gender");

 //  Judge gender 
 String genderText = "";
 if (gender.equals("M")) {
  genderText = " Male ";
 } else {
  genderText = " Female ";
 }

 //  Get a standard weight 
 String weight = getWeight(gender, height);

 //  Set the text content to be displayed 
 TextView textView = findViewById(R.id.textView2);
 textView.setText(" You are 1 Bit " + genderText + "\n Your height is " + height + " Centimeters \n Your standard weight is " + weight + " Kilo ");

 Button button = findViewById(R.id.buttonGoBack);
 button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  //  Set the results and close the page 
  setResult(RESULT_OK, mIntent);
  finish();
  }
 });
 }

 // 4 Shed 5 Formatting 
 private String format(double num) {
 NumberFormat formatter = new DecimalFormat("0.00");
 return formatter.format(num);
 }

 //  Method for calculating standard weight 
 private String getWeight(String gender, double height) {
 String weight = "";
 if (gender.equals("M")) {
  weight = format((height - 80) * 0.7);
 } else {
  weight = format((height - 70) * 0.6);
 }
 return weight;
 }
}

4. Layout of Activity B:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
 <TextView
  android:text="This is the second layout"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/textView2"
  android:paddingTop="30dp"
  android:paddingStart="50dp"/>
 <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:id="@+id/buttonGoBack"
  android:text=" Go back to the top 1 Page "
  android:layout_alignStart="@id/textView2"
  android:layout_below="@id/textView2"
  android:layout_marginTop="54dp" android:layout_marginStart="52dp"/>
</RelativeLayout>

But here are three things to pay attention to:

1. The second parameter requestCode of startActivityForResult passes 0, so let's look at the results of passing values less than 0 and greater than 0 respectively:
(1) Pass a value less than 0, such as-1: equivalent to calling startActivity, onActivityResult will not be called
(2) Pass a value greater than 0, such as 1: The effect is equivalent to passing 0, and the first parameter of onActivityResult is exactly the requestCode we passed through startActivityForResult

2. The second parameter resultCode of onActivityResult: It is returned by the second activity through setResult. There are two commonly used values: RESULT_CANCELED, RESULT_OK
(1) RESULT_CANCELED: Activity B pull-up failure, such as crash
(2) RESULT_OK: Return value after successful Activity B operation

There is also a less commonly used value: RESULT_FIRST_USER. The definition of this value in Android source code is "user-defined activity results" (user-defined). I searched the source code globally, but there are not many places to use. I picked one or two places to use:

(1) InstallFailed. java under PackageInstaller (page related to failed installation of apk)


protected void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 int statusCode = getIntent().getIntExtra(PackageInstaller.EXTRA_STATUS,
  PackageInstaller.STATUS_FAILURE);
 if (getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) {
  //  ... .. 
  setResult(Activity.RESULT_FIRST_USER, result);
  finish();
 }

(2) InstallStaging. java under PackageInstaller


private void showError() {
 (new ErrorDialog()).showAllowingStateLoss(getFragmentManager(), "error");
 //  ... . 
 setResult(RESULT_FIRST_USER, result);
}

UninstallerActivity. java under PackageInstaller (the related page for unloading apk): There are several settings to RESULT_FIRST_USER in the onCreate method.
Therefore, my understanding is that the business itself is used in 1 error or invalid scenario, which is defined by the business itself.

3. If the new_task startup mode is set when starting Activity B, Activity A will immediately call back onActivityResult after entering Activity B, and resultCode is 0; After returning from Activity B setResult, there are no more callbacks to onActivityResult!

The above is Android using startActivityForResult to return data to the first Activity details, more information about Android to return data to the first Activity please pay attention to other related articles on this site!


Related articles: