package com.example.komunitas; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.util.HashMap; public class SessionManager { // Shared Preferences SharedPreferences pref; // Editor for Shared preferences Editor editor; // Context Context _context; // Shared pref mode int PRIVATE_MODE = 0; // Sharedpref file name private static final String PREF_NAME = "AndroidHivePref"; // All Shared Preferences Keys private static final String IS_LOGIN = "IsLoggedIn"; // User name (make variable public to access from outside) public static final String KEY_KODE = "kode"; // Email address (make variable public to access from outside) public static final String KEY_NAMA= "nama"; // Constructor public SessionManager(Context context){ this._context = context; pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); editor = pref.edit(); } /** * Create login session * */ public void createLoginSession(String kode, String nama){ editor.putBoolean(IS_LOGIN, true); editor.putString(KEY_KODE, kode); editor.putString(KEY_NAMA, nama); editor.commit(); } /** * Check login method wil check user login status * If false it will redirect user to login page * Else won't do anything * */ public void checkLogin(){ if(!this.isLoggedIn()){ Intent i = new Intent(_context, Login.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); _context.startActivity(i); } } /** * Get stored session data * */ public HashMap<String, String> getUserDetails(){ HashMap<String, String> user = new HashMap<String, String>(); user.put(KEY_KODE, pref.getString(KEY_KODE, null)); user.put(KEY_NAMA, pref.getString(KEY_NAMA, null)); return user; } public void logout(){ Intent i = new Intent(_context, Login.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); editor.putBoolean(IS_LOGIN, false); editor.putString(KEY_KODE, ""); editor.putString(KEY_NAMA, ""); editor.clear(); editor.commit(); _context.startActivity(i); } public boolean isLoggedIn(){ return pref.getBoolean(IS_LOGIN, false); } }
+++++++++++++++++++++++++++++++++++++
Tidak ada komentar:
Posting Komentar