Created
August 28, 2013 01:55
-
-
Save jpotts18/6361288 to your computer and use it in GitHub Desktop.
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.mydietitian.android.utils; | |
import android.app.Activity; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.SharedPreferences; | |
import android.content.SharedPreferences.Editor; | |
import com.mydietitian.android.activities.LoginActivity; | |
/** | |
* User: jpotts | |
* Date: 8/27/13 | |
* Time: 7:00 PM | |
*/ | |
public class SessionManager { | |
private static SessionManager instance; | |
SharedPreferences pref; | |
Editor editor; | |
Context context; | |
private int PRIVATE_MODE = 0; | |
private static String PREF_NAME = ""; | |
private static final String IS_LOGIN = "IsLoggedIn"; | |
public static final String KEY_TOKEN = "name"; | |
public static final String KEY_EMAIL = "email"; | |
// Constructor | |
private SessionManager(Context context){ | |
this.context = context; | |
PREF_NAME = context.getPackageName(); | |
pref = this.context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); | |
editor = pref.edit(); | |
} | |
public SessionManager getInstance(Context context){ | |
if(instance == null){ | |
instance = new SessionManager(context); | |
} | |
return instance; | |
} | |
public void createLoginSession(String token, String email){ | |
editor.putBoolean(IS_LOGIN, true); | |
editor.putString(KEY_TOKEN, token); | |
editor.putString(KEY_EMAIL, email); | |
editor.commit(); | |
} | |
public void checkLogin(){ | |
// Check login status | |
if(!this.isLoggedIn()){ | |
redirectOnLogout(LoginActivity.class); | |
} | |
} | |
public void logoutUser(){ | |
clearUserSettings(); | |
redirectOnLogout(LoginActivity.class); | |
} | |
public void redirectOnLogout(Class loginActivity){ | |
Intent i = new Intent(context, loginActivity); | |
// clear stack and start new activity | |
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); | |
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
context.startActivity(i); | |
} | |
public void clearUserSettings(){ | |
// Clearing all data from Shared Preferences | |
editor.clear(); | |
editor.commit(); | |
} | |
// Get Login State | |
public boolean isLoggedIn(){ | |
return pref.getBoolean(IS_LOGIN, false); | |
} | |
public String getToken() { | |
return pref.getString(KEY_TOKEN, ""); | |
} | |
public void setToken(String token) { | |
editor.putString(KEY_TOKEN, token); | |
editor.commit(); | |
} | |
public String getEmail(){ | |
return pref.getString(KEY_EMAIL, ""); | |
} | |
public void setEmail(String email) { | |
editor.putString(KEY_EMAIL, ""); | |
editor.commit(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment