从SharedPreferences加载存储的json

时间:2014-02-18 17:19:54

标签: android sharedpreferences gson

问题

这个问题已经困扰了我很长一段时间。这种情况并不常见,但确实会不时发生。问题如下:

我在SharedPreferences中的s Gson序列化对象中保存了一堆用户首选项。这条路, 当我需要该对象时,我将其加载到内存中,仅执行1次存储调用。但是,由于一些奇怪的原因,我收到了这个错误:

java.lang.RuntimeException: Unable to resume activity {com.a.b/com.a.b.SomeActivity}: java.lang.RuntimeException: unable to parse type class com.a.b.storage.SomeClass$AppSettings with json: rialFinished":false,"lastOpenedAppId":0,"appVersion":35,"tutorialFinished":false}

可以看出,json没有正确加载,它是一个无效的json,所以试图解析它只会引发异常。

其他一些事实

  • 抛出的每个异常都会显示完全相同的json解析问题。出于某种原因,总是正在加载的字符串:

rialFinished":false,"lastOpenedAppId":0,"appVersion":35,"tutorialFinished":false}

  • 这不是“设备特定问题”,或者至少我是这么认为的。证据: enter image description here
    如您所见,它并非特定于设备。我也知道它不是特定于Android版本的事实,我们已经从Android 2.3.64.0.34.1.14.1.2,{{ 1}}

  • 序列化的类是

    4.0.4
  • 用于加载json的方法是:

    class AppSettings {
    
    private boolean tutorialFinished;
    private boolean googleAuthTutorialFinished;
    private int appVersion;
    private int lastOpenedAppId;
    
    public AppSettings() {
        tutorialFinished = false;
        appVersion = NO_STORED_VERSION;
        googleAuthTutorialFinished = false;
    }
    
    public boolean isTutorialFinished() {
        return tutorialFinished;
    }
    
    public void setTutorialFinished(boolean tutorialFinished) {
        this.tutorialFinished = tutorialFinished;
    }
    
    public void setAppVerions(int appVerions) {
        this.appVersion = appVerions;
    }
    
    public void setGoogleAuthTutorialFinished(boolean googleAuthTutorialFinished) {
        this.googleAuthTutorialFinished = googleAuthTutorialFinished;
    }
    
    /**
     *
     * @return the stored app version or {@link AppSettingsStorage#NO_STORED_VERSION} if none was found
     */
    public int getAppVerions() {
        return appVersion;
    }
    
    public boolean isGoogleAuthTutorialFinished() {
        return googleAuthTutorialFinished;
    }
    
    public int getLastOpenedAppId() {
        return lastOpenedAppId;
    }
    
    public void setLastOpenedAppId(int lastOpenedAppId) {
        this.lastOpenedAppId = lastOpenedAppId;
    }
    
    }
    

可能的原因:

1 个答案:

答案 0 :(得分:0)

你错过了双引号吗?

unable to parse type class com.a.b.storage.SomeClass$AppSettings with json: 

rialFinished":false,"lastOpenedAppId":0,"appVersion":35,"tutorialFinished":false}

应该是:

unable to parse type class com.a.b.storage.SomeClass$AppSettings with json: 

"rialFinished":false,"lastOpenedAppId":0,"appVersion":35,"tutorialFinished":false}