Gson枚举因重新启动应用程序而丢失值

wz1wpwve  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(216)

我正在开发一款游戏,在玩的时候会有一些效果

  1. public enum Effect {
  2. DoublePoints(),
  3. IncreaseSwitch(),
  4. ShowOne(),
  5. ShowSame();
  6. @SerializedName("stored")
  7. int stored;
  8. @SerializedName("leftTime")
  9. int leftTime;
  10. Effect() {
  11. }
  12. public int getStored() {
  13. return stored;
  14. }
  15. public void setStored(int stored) {
  16. this.stored = stored;
  17. }
  18. public int getLeftTime() {
  19. return leftTime;
  20. }
  21. public void setLeftTime(int leftTime) {
  22. this.leftTime = leftTime;
  23. }
  24. }

stored i检查我具有的效果的计数,并且leftTime是直到效果结束的时间。
为了有效地读取和写入,我使用HashMap在运行时处理效果

  1. private Map<String, EnumCollection.Effect> gameEffects = new HashMap<>();

并将其存储为数据库中的String
现在我用Gson来解析效果 * 从字符串 * 通过游戏的初始化和 * 到字符串 * 通过保存。

  1. // read
  2. public void setEffects() {
  3. if (game.getEffects() == null) {
  4. gameEffects.put(EnumCollection.Effect.DoublePoints.toString(), EnumCollection.Effect.DoublePoints);
  5. EnumCollection.Effect switchEffect = EnumCollection.Effect.IncreaseSwitch;
  6. switchEffect.setLeftTime(3);
  7. gameEffects.put(EnumCollection.Effect.IncreaseSwitch.toString(), switchEffect);
  8. gameEffects.put(EnumCollection.Effect.ShowOne.toString(), EnumCollection.Effect.ShowOne);
  9. gameEffects.put(EnumCollection.Effect.ShowSame.toString(), EnumCollection.Effect.ShowSame);
  10. } else {
  11. Type collectionType = new TypeToken<HashMap<String, EnumCollection.Effect>>() {
  12. }.getType();
  13. gameEffects = new Gson().fromJson(game.getEffects(), collectionType);
  14. }
  15. }
  16. // write
  17. private void saveGameValues() {
  18. String effectsString = new Gson().toJson(gameEffects);
  19. ...
  20. }

现在就去
我可以成功地关闭和打开应用程序。数据写入和读取成功的数据库。
通过重新打开应用程序,我得到了我所期望的 storedleftTime 值。
"但是...“
一旦我使用Android Studio重新运行按钮 * 重新启动 * 应用程序,storedleftTime 为0。
当记录字符串接收到的影响时:

  1. effects: {"ShowSame":"ShowSame","DoublePoints":"DoublePoints","ShowOne":"ShowOne","IncreaseSwitch":"IncreaseSwitch"}

对于@SerializedName,是否应存储值?
我错过了什么?
难道是TypeToken有什么问题?

kxe2p93d

kxe2p93d1#

通过从enumObject求解

  1. public class EffectItem {
  2. int stored;
  3. int leftTime;
  4. public int getStored() {
  5. return stored;
  6. }
  7. public void setStored(int stored) {
  8. this.stored = stored;
  9. }
  10. public int getLeftTime() {
  11. return leftTime;
  12. }
  13. public void setLeftTime(int leftTime) {
  14. this.leftTime = leftTime;
  15. }
  16. }

从那

  1. Type collectionType = new TypeToken<HashMap<String, EffectItem>>() {
  2. }.getType();
  3. gameEffects = new Gson().fromJson(game.getEffects(), collectionType);

工作正常。HashMap

  1. private Map<String, EffectItem> gameEffects = new HashMap<>();

仍然可以用来更好地获得效果

展开查看全部

相关问题