我有三项活动。
我的问题是,我无法找到一种方法将该数字从A传递给B,并且当用户从C重置B时保存该数字。我尝试了一些方法,但我无法使其工作。 我的代码:
A:
long npsum = npint * 60000 + np3int * 1000;
Intent cardintent = new Intent(getApplicationContext(), card_game_2.class);
cardintent.putExtra("card2string",npsum);
startActivity(cardintent);
B:
Bundle card2extras = getIntent().getExtras();
if (card2extras != null) {
String startcardstring = card2extras.getString("card2string");
startcard = Long.parseLong(startcardstring);
}
C:
Intent resetintent = new Intent(card_2_pause.this, card_game_2.class);
startActivity(resetintent);
感谢您的帮助
答案 0 :(得分:4)
启动Pause Activity C时可以使用startActivityForResult()。startActivityForResult()使您可以将数据发送到接收活动,在您的情况下是MainActivity C.请参阅tutorial here
答案 1 :(得分:1)
修正了它。新代码:
A:
GROUP BY
B:
Intent timerdintent = new Intent(timer_settings.this, timer_2.class);
Bundle timer2extras = new Bundle();
timer2extras.putString("timer2string", String.valueOf(npsum));
timerdintent.putExtras(timer2extras);
startActivity(timerdintent);
C:
SharedPreferences pref = getApplicationContext().getSharedPreferences("timer2stringpref", MODE_PRIVATE);
Bundle timer2extras = getIntent().getExtras();
if (timer2extras != null) {
String timer2string = timer2extras.getString("timer2string");
starttimer = Integer.parseInt(timer2string);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("value", starttimer);
editor.apply();
} else {
int starttimerx = pref.getInt("value", 0);
starttimer = starttimerx;
}
答案 2 :(得分:0)
您还可以设置(数据)片段来交换数据吗?
在其onCreate集中 setRetainInstance(真);
为你的card2string
添加一些setter / getters并在不同的活动中通过以下方式获取它的实例:
例如MainActivity
public final static String DATAFRAG = "DATA";//public so you can use it from any Activity
在例如onCreate或您需要数据的位置:
FragmentManager fm = getFragmentManager();
dataFrag = (DataFragment) fm.findFragmentByTag(MainActivity.DATAFRAG);
if (dataFrag == null)
{
dataFrag = new DataFragment();
dataFrag.setCard2String("something");
fm.beginTransaction().add(dataFrag, MainActivity.DATAFRAG).commit();
}
确保在DataFragment中覆盖
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
}
并在onCreate中使用Bundle来保存&在片段被销毁的情况下恢复您的数据...
HTH