[英]How to save a serialized object state when I am passing it using Intent
我有以下課程:
public class Creature implements Serializable {
protected String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
// Rest of the methods and variables
}
玩家職業擴展了生物:
public class Player extends Creature implements Serializable {
// Class code
}
我正在使用Intents
將Player
實例從一個活動傳遞到另一個活動:
// Activity A, passing the object
Intent charActivity= new Intent(this, CharacterActivity.class);
charActivity.putExtra("Player", player);
startActivity(goToCharacterActivity);
// Activity B, grabbing the object
Player player = (Player) getIntent().getSerializableExtra("Player");
現在,如果我做類似player.setName("Hello");
在活動B中,“原始”對象名稱不會更新,新名稱僅在此當前活動中有效,因為我只有該對象的本地“副本”。 如果必須使用Serializable,該如何解決?
如果希望它們引用內存中的同一對象,則不能使用Serializable
或Parcelable
。 (將在內存中自動創建一個新的對象)。
在這種情況下,我建議您使用一個共享類,其中包含保存您的信息的靜態字段。 例如:
SharedInfo:
public class SharedInformation {
public static Creature theCreature;
}
活動A:照常開始使用Intent,但不要通過Person
或Creature
活動B:
SharedInformation.theCreature.setName("Hello");
我在github中有一個播放器列表示例。 我所做的是使用onActivityResult和startActivityForResult方法,這些方法允許在兩個活動之間返回值。 您可以查看完整的示例並從我的github repoitory下載代碼。
因為您的意圖名稱不相同。
Intent charActivity= new Intent(this, CharacterActivity.class);
您使用charActivity
作為名稱。
更改
startActivity(goToCharacterActivity);
至
startActivity(charActivity);
如果您想在活動之間傳遞,請嘗試像這樣的捆綁
活動1:
Intent i = new Intent(this,CharacterActivity.class);
Bundle playerBundle = new Bundle();
playerBundle.putSerializable("Player",player);
i.putExtras(playerBundle);
startActivity(i);
這是在活動2處檢索捆綁包的方法:
Player player = (Player) getIntent.getSerializableExtra("Player");
並記住在此示例中,該意圖之間的關鍵必須相同
作為關鍵
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.