简体   繁体   中英

Unable to load data from Shared Preferences after app update

I have an app on the play store where Shared Preference entries are stored as json strings. I'm trying to update the app but I noticed that I'm unable to load any of the stored shared preference data correctly after the app is updated, meaning all the user's stored preferences will be lost if they update.

So say I have a class like this:

public class BrightnessSetting {
    public int systemAutoBrightness;
    public boolean customAutoBrightness;
    public int brightnessLevel;
    public float adjustmentLevel;
    public boolean playSound;
    public String soundFile;
}

Objects of this class are saved to the app's shared preferences in json format, which just transforms it into a long string. When the release app bundle is generated it shrinks this string down by replacing the variable names with letters because it's using ProGuard. Meaning the end result will be like this: {"a": 0, "b": false, "c": 25, "d": 0.0, "e": false} . After testing I found that without ProGuard everything works fine, but with ProGuard I'm no longer able to retrieve the data after the app is updated. The Shared Preference keys are still correct, and their corresponding json strings are still correct, but when I try to transform the json string back into its original form as a BrightnessSetting object then I get an empty object.

How can I get the original object back from the json string?

Add this to your proguard config:

-keepclassmembernames class your.path.to.BrightnessSetting

If you are using Gson to convert your class to and from a string, you need to prevent proguard from obfuscating the class's members (which Gson needs in order to work).

Ideally, you should store your information in another way so as to not have to rely on this method. Any changes to BrightnessSetting between updates could potentially break backwards compatibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM