dependencies {
compile 'com.google.code.gson:gson:2.2.4'
}
Last active
August 29, 2015 14:02
-
-
Save dmytrodanylyk/df775f64be28a0d149c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Android Preferences |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PreferencesManager { | |
private Context mContext; | |
private static final String PREF_NAME = "pref.mykatch"; | |
private static final String USER = "user"; | |
public PreferencesManager(Context context) { | |
mContext = context; | |
} | |
public SharedPreferences preferences() { | |
return mContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); | |
} | |
public void clear() { | |
preferences().edit().clear().commit(); | |
} | |
@Nullable | |
public User getUser() { | |
String userJsonString = preferences().getString(USER, null); | |
User user = null; | |
if (userJsonString != null) { | |
user = User.fromJson(userJsonString); | |
} | |
return user; | |
} | |
public void setUser(@NotNull User user) { | |
preferences().edit().putString(USER, user.toJson()).commit(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class User { | |
@SerializedName("id") | |
private long id; | |
@SerializedName("access_token") | |
private String accessToken; | |
@SerializedName("avatar") | |
private String avatar; | |
@SerializedName("name") | |
private String name; | |
@SerializedName("bio") | |
private String bio; | |
@NotNull | |
public static User fromJson(@NotNull String json) { | |
Gson gson = new Gson(); | |
return gson.fromJson(json, User.class); | |
} | |
@NotNull | |
public static User fromJson(@NotNull JSONObject json) { | |
return fromJson(json.toString()); | |
} | |
@NotNull | |
public String toJson() { | |
Gson gson = new Gson(); | |
return gson.toJson(this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment