在父 activity 中使用 startActivityForResult() 时,如何获得通过多个活动传递的额外信息?

How to get extra that is passed through several activities when using startActivityForResult() in parent activity?

我想制作一个测验应用程序。活动流程如下: MainActivity -> ProfileActivity -> NewProfileActivity -> QuestionActivity -> ResultActivity -> Main Activity.

在配置文件Activity 上,它将显示一个名称列表(使用 recyclerview)。它有一个调用 startActivityForResult() 的按钮。在 NewProfileActivity 上,它有一个按钮可以将额外的字符串发送回 ProfileActivity。

问题是,我不希望 NewProfileActivity 返回到 ProfileActivity。如何通过几个活动传递extra然后显示在ProfileActivity?

个人资料中Activity

    Intent intent = getIntent();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(ProfileActivity.this, NewProfileActivity.class);
            startActivityForResult(intent, NEW_PROFILE_ACTIVITY_REQUEST_CODE);
        }
    });

在ActivityResult()方法中

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == NEW_PROFILE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
        Profile profile = new Profile(intent.getStringExtra("profile_name"));
        mProfileViewModel.insert(profile);
    } else {
        Toast.makeText(getApplicationContext(),
                R.string.empty_not_saved,
                Toast.LENGTH_LONG).show();
    }
}

在新配置文件中Activity

final Button save_profile_button = findViewById(R.id.button_save);
    save_profile_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String profile_name = mProfileNameView.getText().toString();
            Intent intent = new Intent(NewProfileActivity.this, QuestionActivity.class);
            intent.putExtra("profile_name_extra", profile_name);
            startActivity(intent);
        }
    });

为简单起见,对于其余活动,我通过将此代码放在 onCreate 方法中来传递额外内容:

Intent intent = getIntent();
    final String profile_name = intent.getStringExtra("profile_name_extra");

在按钮上,我输入了这段代码:

Intent intent = new Intent(QuestionActivity.this, ResultActivity.class);
            intent.putExtra("profile_name_extra", profile_name);

您可以将数据放入 sharedPreferences 对象,然后在任何 Activity 中取回它。这样您就可以避免在多个活动之间来回传递数据的开销。 因此,在您的 NewProfileActivity 中,将额外内容保存到 sharedPreferences 中,然后在您想要的任何地方再次获取它。 可在此处找到有关从 sharedPreferences 写入和读取数据的文档

https://developer.android.com/training/data-storage/shared-preferences

希望这对您有所帮助。