我试图在切换到另一个活动时在“MainActivity”中保存一些数据,并在我切换回它时恢复这些数据。
在“MainActivity”中:(恢复数据)
protected void onCreate(Bundle savedInstanceState) {
// do usual stuff
restoreData();
}
在“MainActivity”中:(切换到“StatusActivity”):
Bundle data = saveData();
Log.d(TAG, "Sending data to status activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), StatusActivity.class);
intent.putExtras(data);
startActivity(intent);
在“状态活动”中:
Bundle data = getIntent().getExtras();
Log.d(TAG, "Sending data to main activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtras(data);
startActivity(intent);
我的 saveData() 函数:
private Bundle saveData() {
Log.d(TAG, "Started saving state");
Bundle data = new Bundle();
// store stuff in the bundle
return data;
}
我的 restoreData() 函数:
private void restoreData() {
Log.d(TAG, "Started restoring state");
Bundle data = getIntent().getExtras();
// restore stuff in the bundle
}
日志猫:
发送到 StatusActivity 时,我的捆绑包很好:
Sending data to status activity intent:
Bundle[{obj0=Bundle[{timeSinceLastPooped=3224, hunger=5,
id=2130837505, timeSinceLastHungerUpdate=3224,
timeSinceLastFed=0, timeSinceLastHappinessUpdate=3224,
timeSinceLastEvolution=3224, posY=0.0, posX=0.0,
isDead=false, happiness=5, evolutionStage=0, type=pet}],
time=7.794168E7}]
但随后发送回 MainActivity:
Sending data to main activity intent: Bundle[mParcelledData.dataSize=648]
我如何使用 mParcelledData 来取回原始捆绑包?谢谢!
回答:
在“MainActivity”中:(恢复数据)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == 1) {
if(resultCode == RESULT_OK) {
restoreData(intent);
}
}
}
在“MainActivity”中:(切换到“StatusActivity”):
Bundle data = saveData();
Log.d(TAG, "Sending data to status activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), StatusActivity.class);
intent.putExtras(data);
startActivityForResult(intent, 1);
在“状态活动”中:
Bundle data = getIntent().getExtras();
Log.d(TAG, "Sending data to main activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtras(data);
setResult(RESULT_OK, getIntent());
finish();