[英]How to return to previous activity that has an extra from another activity
A --> B --> C --> back to B A --> B --> C --> 回到 B
Where A must send an extra to B and B has a button (back button) to C. When pressing the back button from C, it must go back to B, that still has the extra from A. Basically, B and C go back and forth, where both stay the same when left, without data being destroyed.其中 A 必须向 B 发送额外信息,B 有一个按钮(后退按钮)到 C。当从 C 按下后退按钮时,它必须返回到 B,仍然有来自 A 的额外信息。基本上,B 和 C 返回来回,当离开时两者保持不变,没有数据被破坏。
However, in my case, it goes back to A and if I use finish()
or startActivity()
the app crashes, saying it's NullPointerException.但是,在我的情况下,它返回到 A,如果我使用finish()
或startActivity()
应用程序崩溃,说它是 NullPointerException。 I figured this is because B hasn't received any extra from A, because it was C that was calling B.我想这是因为 B 没有从 A 那里收到任何额外的信息,因为是 C 打电话给 B。
Should I pass the A's extra from B to C and back to B again?我是否应该将 A 的多余部分从 B 传递给 C,然后再返回给 B? What should one do?一个人应该怎么做?
A一种
String indicate = textView.getText().toString();
Intent t = new Intent(getApplicationContext(), Details.t.putExtra("indicate", indicate);
startActivity(t);
finish();
B (onCreate()) B (onCreate())
Intent g = getIntent();
String indica = g.getExtras().getString("indicate");
TextView diseaseLabel = (TextView) findViewById(R.id.statusTxt);
diseaseLabel.setText(indica);
C C
public boolean onOptionsItemSelected(MenuItem item) {
//finish();
//Intent i = new Intent(this.context, B.class);
//startActivity(i);
return super.onOptionsItemSelected(item);
}
One approach you can do is save your indicate
to SharedPreferences
thru PreferenceManager.getDefaultSharedPreferences(Context context)
so you don't keep on passing things around.您可以做的一种方法是通过PreferenceManager.getDefaultSharedPreferences(Context context)
将您的indicate
保存到SharedPreferences
这样您就不会继续传递信息。
However as the name suggests, this is usually used for Preferences or Settings.然而,顾名思义,这通常用于首选项或设置。 But you get the idea, right?但是你明白了,对吧?
You need to use startActivityForResult in order to return to B activity without data being destroyed.您需要使用 startActivityForResult 以便在不破坏数据的情况下返回 B 活动。
For example when you are on B activity start C activity with the following code例如,当您进行 B 活动时,使用以下代码启动 C 活动
Intent intent = new Intent(B.this, C.class);
startActivityForResult(intent, REQUEST_RESULT_CODE); //suppose resultCode == 2;
and when you need to go back to B activity use the following code当您需要返回 B 活动时,请使用以下代码
public boolean onOptionsItemSelected(MenuItem item)
{
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
return super.onOptionsItemSelected(item);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.