Skip to content

Instantly share code, notes, and snippets.

@m7mdra
Created April 7, 2017 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m7mdra/0052c49e73e66e38a500e3e3eb361c2a to your computer and use it in GitHub Desktop.
Save m7mdra/0052c49e73e66e38a500e3e3eb361c2a to your computer and use it in GitHub Desktop.
stores user and token
package com.reqabaweb.healthcontrol;
import android.content.Context;
import android.content.SharedPreferences;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by allaeem on 4/7/2017.
*/
public class UserPreference {
private static UserPreference userPreference;
private SharedPreferences preference;
private static final String KEY_TOKEN = "TOKEN";
private static final String KEY_USER = "USER";
private UserPreference(Context context) {
preference=context.getSharedPreferences("UserPreference",Context.MODE_PRIVATE);
}
public static UserPreference getPreference(Context context){
if (userPreference==null)
userPreference=new UserPreference(context);
return userPreference;
}
public void saveUser(String jsonData){
SharedPreferences.Editor editor=preference.edit();
editor.putString(KEY_USER,jsonData);
try {
JSONObject object=new JSONObject(jsonData);
String token = object.optString("token");
editor.putString(KEY_TOKEN,token);
} catch (JSONException e) {
e.printStackTrace();
}
editor.apply();
}
public String getUser(){
return preference.getString(KEY_USER,"");
}
public String getToken(){
return preference.getString(KEY_TOKEN,"");
}
public void removeAll(){
SharedPreferences.Editor edit = preference.edit();
edit.remove(KEY_TOKEN);
edit.remove(KEY_USER);
edit.apply();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment