How can I pass values between Activities on Android?

前端 未结 6 1192
轮回少年
轮回少年 2020-11-30 02:09

This is the navigation of my application:

Activity1 calls Activity2Activity2.finish(), call Activ

6条回答
  •  猫巷女王i
    2020-11-30 02:26

    Umesh shows a good technique but I think you want the opposite direction.

    Step 1

    When starting Activity 2 and 3, use startActivityForResult. This allows you handle the result in the calling activity.

    startActivityForResult(MY_REQUEST_ID);
    

    Step 2

    In Activities 2 and 3, call setResult(int, Intent) to return a value:

    Intent resultData = new Intent();
    resultData.putExtra("valueName", "valueData");
    setResult(Activity.RESULT_OK, resultData);
    finish();
    

    Step 3

    In your calling activty, implement onActivityResult and get the data:

    protected void onActivityResult(int requestCode, int resultCode,
              Intent data) {
          if (requestCode == MY_REQUEST_ID) {
              if (resultCode == RESULT_OK) {
                String myValue = data.getStringExtra("valueName"); 
                // use 'myValue' return value here
              }
          }
    }
    

    Edit:

    Technique #2

    Yes, you can also use global application state by adding a class to your application that extends Application, see this StackOverflow answer

提交回复
热议问题