Navigating from Activity A->B->C - How to pass data from C to A in onBackPressed()?

前端 未结 3 1313
春和景丽
春和景丽 2021-01-15 18:37
  1. From Activity A call Activity B
  2. from B to C and while calling Activity C
  3. I call finish for Activity B
相关标签:
3条回答
  • 2021-01-15 18:50

    Don't call finish() from B when opening C. Instead, call C with startActivityforResult() and then pass the data back through B when onActivityResult() in B is triggered. Something like:

    ActivityB {
        onCreate(Bundle) {
            startActivityForResult(ActivityC, 0);
        }
    
        onActivityResult(int, int, Intent){
            setResult(resultCode, data);
            finish();
        }
    }
    

    Edit:

    Apparently adding the flag Intent.FLAG_ACTIVITY_FORWARD_RESULT when calling B should actually achieve your desired result as well.

    Learn somethin' new every day...

    0 讨论(0)
  • 2021-01-15 18:56

    use shared preference

    C ACTIVITY

    SharedPreferences sf = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sf.edit(); editor.putString(key, value); editor.commit();

    A ACTIVITY

    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); String savedPref = sharedPreferences.getString(key, ""); mOutputView.setText(savedPref);

    0 讨论(0)
  • 2021-01-15 19:05

    Where're multiple ways of doing this:

    • Store the data from Activity C to Application's object and just read it in Activity A:

         ((MySuperApplication) getApplication()).setMyData(..);
      
    • Pass it as Activity Result

    • Store data to SharedPreference in Activity C and read it in Activity A. If it's a complex data structure - I'd suggest to use gsonto serialize object and store it as a string and then deserialize it in Activity A

    Choose the one you like the most.

    0 讨论(0)
提交回复
热议问题