Created
December 12, 2017 00:47
-
-
Save diefferson/b699b345f94edab46793a76d10ac66c1 to your computer and use it in GitHub Desktop.
Android Preferences Example
This file contains hidden or 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
package com.eventifly.core.data.prefs; | |
import android.content.Context; | |
import android.content.SharedPreferences; | |
import com.eventifly.core.data.model.Profile; | |
import com.eventifly.core.data.model.Settings; | |
import com.eventifly.core.data.model.Tag; | |
import com.eventifly.core.data.ws.RestClient; | |
import com.eventifly.core.data.ws.response.AuthLoginResponse; | |
import java.util.List; | |
public class Preferences { | |
private static final String USER_PREFERENCES = "preferences_filename.preferences"; | |
private static final String PROFILE_UUID_KEY = "profile-uuid"; | |
private static final String PROFILE_NAME_KEY = "user-name"; | |
private static final String PROFILE_AVATAR_KEY = "user-avatar"; | |
private static final String AUTH_TOKEN = "auth-token"; | |
private static final String AUTH_EXPIRES = "auth-expires"; | |
private static final String AUTH_REFRESH = "auth-refresh"; | |
private SharedPreferences mPreferences; | |
public Preferences(Context context) { | |
mPreferences = context.getSharedPreferences(USER_PREFERENCES, Context.MODE_PRIVATE); | |
} | |
public void saveProfile(Profile profile) { | |
mPreferences.edit() | |
.putString(PROFILE_UUID_KEY, profile.getUuid()) | |
.putString(PROFILE_NAME_KEY, profile.getName()) | |
.putString(PROFILE_AVATAR_KEY, profile.getAvatar()) | |
.commit(); | |
} | |
public void saveAuth(AuthLoginResponse auth) { | |
mPreferences.edit() | |
.putString(AUTH_TOKEN, auth.getAccessToken()) | |
.putLong(AUTH_EXPIRES, auth.getExpiresIn()) | |
.putString(AUTH_REFRESH, auth.getRefreshToken()) | |
.commit(); | |
} | |
public boolean isLogged() { | |
return mPreferences.contains(AUTH_TOKEN) && !mPreferences.getString(AUTH_TOKEN, "").isEmpty(); | |
} | |
public Profile getProfile() { | |
Profile profile = new Profile(); | |
profile.setUuid(mPreferences.getString(PROFILE_UUID_KEY, "")); | |
profile.setName(mPreferences.getString(PROFILE_NAME_KEY, "")); | |
profile.setAvatar(mPreferences.getString(PROFILE_AVATAR_KEY, "")); | |
return profile; | |
} | |
public String getAuthToken() { | |
return mPreferences.getString(AUTH_TOKEN, ""); | |
} | |
public String getAuthTokenWithPrefix() { | |
return mPreferences.getString(mPreferences.getString(AUTH_TOKEN, ""); | |
} | |
public String getUUID() { | |
return mPreferences.getString(PROFILE_UUID_KEY, ""); | |
} | |
public void clear() { | |
mPreferences.edit().clear().apply(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment