Can anybody tell me how to maintain session for a user login. For example when the user sign- in to an application they have to be signed in unless the user logouts or uninstall the application similar to gmail in android.
Make one class for your SharedPreferences
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
prefs.edit().putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
Now after making this class when you want to use it, use like this: make object of this class like
private Session session;//global variable
session = new Session(cntx); //in oncreate
//and now we set sharedpreference then use this like
session.setusename("USERNAME");
now whenever you want to get the username then same work is to be done for session object and call this
session.getusename();
Do same for password
You can achieve this by using AccountManager.
Code Sample
// method to add account..
private void addAccount(String username, String password) {
AccountManager accnt_manager = AccountManager
.get(getApplicationContext());
Account[] accounts = accnt_manager
.getAccountsByType(getString(R.string.account_type)); // account name identifier.
if (accounts.length > 0) {
return;
}
final Account account = new Account(username,
getString(R.string.account_type));
accnt_manager.addAccountExplicitly(account, password, null);
final Intent intent = new Intent();
intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
intent.putExtra(AccountManager.KEY_PASSWORD, password);
intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,
getString(R.string.account_type));
// intent.putExtra(AccountManager.KEY_AUTH_TOKEN_LABEL,
// PARAM_AUTHTOKEN_TYPE);
intent.putExtra(AccountManager.KEY_AUTHTOKEN, "token");
this.setAccountAuthenticatorResult(intent.getExtras());
this.setResult(RESULT_OK, intent);
this.finish();
}
// method to retrieve account.
private boolean validateAccount() {
AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> arg0) {
Log.e("calback", "msg");
try {
Bundle b = arg0.getResult();
if (b.getBoolean(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE)) {
//User account exists!!..
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
AccountManager accnt_manager = AccountManager
.get(getApplicationContext());
Account[] accounts = accnt_manager
.getAccountsByType(getString(R.string.account_type));
if (accounts.length <= 0) {
return false;
} else {
loginNameVal = accounts[0].name;
loginPswdVal = accnt_manager.getPassword(accounts[0]);
return true;
}
}
I have one simple way rather than maintain a session.
i.e. Just store one boolean variable with your username and password. by default set value equal to false.
After first successful login make its value to true.
Then just check its value on your Mainactivity, if it is true then jump to next activity otherwise jump to login activity.
You can use a boolean value in the SharedPreferences.
Load it before login to check if login is needed.
Save it after login.
Use SharedPreferences.
Code to save a value to sharedpreferences:
SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
SharedPreferences.Editor ed=sp.edit();
ed.putInt("value", your_value);
ed.commit();
Code to get value from sharedpreferences:
SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
int value = sp.getInt("value", default_value);
You can check login and logout by using this value.
You can obtain that behaivour in a few different ways, the one I prefer is setting a flag in the shared prefs. whe a user logs in an check it when the app is started if you get the default value the user is not loggend, else you should have your flag (i use the user name) set and avoid the log-in section.
save the user data in shared preferences till the user logs out.
once user logs out clear the data from shared preferences.
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
editor = prefs.edit();
}
public void setusename(String usename) {
editor.putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUcUZxeHo0UnJ5UHc
Fetch Previous Login ID in android
**After Login save Email ID is SharedPreferences**
emaidId = et_Email.getText().toString().trim();
SharedPreferences ss = getSharedPreferences("loginSession_key", 0);
Set<String> hs = ss.getStringSet("set", new HashSet<String>());
hs.add(emaidId);
SharedPreferences.Editor edit = ss.edit();
edit.clear();
edit.putStringSet("set", hs);
edit.commit();
===================onCreate()====================
===================AutoCompleteTextView set Adapter===================
**Fetch PRevious Login Email id in email EditText**
SharedPreferences sss = getSharedPreferences("loginSession_key", 0); // todo loginSession_key key name ALWAYS SAME
Log.i("chauster", "2.set = " + sss.getStringSet("set", new HashSet<String>()));
Log.e("Session", "Value->" + sss.getStringSet("set", new HashSet<String()));
ArrayList<String> al = new ArrayList<>();
al.addAll(sss.getStringSet("set", new HashSet<String>()));
//Creating the instance of ArrayAdapter containing list of language names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, al);
//Getting the instance of AutoCompleteTextView
et_Email.setThreshold(1);//will start working from first character
et_Email.setAdapter(adapter);//setting the adapter data into the
Using this class will help you to store all types of sessions
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void set(String key,String value) {
prefs.edit().putString(key, value).commit();
}
public String get(String key) {
String value = prefs.getString(key,"");
return value;
}
}
Through this format, you can set or get multiple objects of data, you don't need to create separate functions to store different models in SharedPreferences.
* Here in this format, you don't need to pass your object KEY for putString() and getString()
* Using the object class name you are able to identify your session object uniquely, for both setModel() and getModel()
public class Session {
private final SharedPreferences pref;
public Session(Context ctx) {
pref = PreferenceManager.getDefaultSharedPreferences(ctx);
//pref = ctx.getSharedPreferences("IDENTIFIED_NAME", Context.MODE_PRIVATE);
}
public <U> void setModel(U obj) {
pref.edit().putString(getClassName(obj), SerializeObject(obj)).apply();
}
/* Parameter Example: Class.class */
public <U> U getModel(Class<U> type) {
String user = pref.getString(type.getSimpleName(), null);
if (isEmptyOrNull(user)) {
return null;
}
return DeserializeObject(user, type);
}
/* The below functions are for support, You can move the below part to your own BaseUtil class. */
public static boolean isEmptyOrNull(String data) {
if (data == null) {
return true;
}
if (data.isEmpty() || data.trim().isEmpty()) {
return true;
}
return false;
}
public static String getClassName(Object obj) {
return obj.getClass().getSimpleName();
}
public static String SerializeObject(Object myObject) {
// serialize the object
try {
Gson gson = new Gson();
String json = gson.toJson(myObject);
return json;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public static <U> U DeserializeObject(String serializedObject, Class<U> type) {
// serialize the object
try {
if (serializedObject == null || serializedObject.isEmpty()) {
return null;
}
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
U data = gson.fromJson(serializedObject, type);
return data;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
}
Create an object class (file_name: UserModel.java)
public class UserModel {
public String userId;
public String firstName;
public String lastName;
public String email;
public String phone;
}
How to use - For setModel() and getModel()
//creating an instance of the Session class
Session session = new Session(ctx); // Here you have to pass the Context(ctx)
// setting value in the UserModel
UserModel obj = new UserModel();
obj.firstName = "Apu";
obj.lastName = "Pradhan";
obj.email = "godfindapu#gmail.com";
obj.phone = "123456789";
// set UserModel in the Session
session.setModel(obj);
//getting UserModel data from the Session
UserModel userData = session.getModel(UserModel.class);
Related
I'm trying to save a string to shared preferences and then start an activity and retrieve it but doesn't work. What am I doing wrong?
First I set the shared preference key then I start the activity:
SharedPreferences.Editor editor =
getSharedPreferences("PaymentStatus",MODE_PRIVATE).edit();
editor.putString("payment_status","success");
editor.apply();
Intent i = new Intent(getBaseContext(), ProfileActivity.class);
startActivity(i);
and on the ProfileActivity class I trying to retrieve the key:
SharedPreferences prefs = getSharedPreferences("PaymentStatus",
MODE_PRIVATE);
String payment_status = prefs.getString("payment_status", null);
if(payment_status == "success"){
Log.i("payment status", "success");
}
I can't see the payment status success in the logcat.
The issue with the code you have given is not with how you done it with shared preferences (you did that correctly btw)
Your issue is that you are comparing strings via == as this compares the string reference and not the string value. Use .equals() or .contains() instead.
if (payment_status.equals("success")) {
Log.i("payment status", "success");
}
This is my experience in used SharedPreferens.
Perhaps this approach will solve the problem:
public class UserData {
UserData(MainActivity mainActivity){this.mainActivity = mainActivity;}
private static UserData userData;
private final MainActivity mainActivity;
private SharedPreferences sPref;
private SharedPreferences.Editor editor;
final private String USER_ID = "user_id";
public static void create(MainActivity activity) {
if (userData == null) userData = new UserData(activity);
}
public static UserData getUserData() {
return userData;
}
void createUser() {
sPref = mainActivity.getSharedPreferences("UserData", Context.MODE_PRIVATE);
editor = sPref.edit();
// Если user id уже есть, выходим из метода
if(sPref.contains(USER_ID)) return;
editor.putString(USER_ID, createUserId());
editor.apply();
Toast.makeText(mainActivity,"UserId created", Toast.LENGTH_SHORT).show();
}
// id формируется на основе текущей даты и времени
private String createUserId() {
Date currentDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmmss", Locale.getDefault());
return dateFormat.format(currentDate);
}
public String getUserId() {
return sPref.getString(USER_ID, "");
}
}
I want to clear the data I am getting from SharedPreference, I try the following answer but didn't make my task:
1) how to delete sharedpreferences ,Quit and launch application from first actvity in android
2) clear the value of sharedpreferences
3) Remove Shared preferences key/value pairs
4) SharedPreferences Clear/Save
they are all removing value, after they write data into SharedPreference, like editor.remove and .clear...
I have write data into SharedPreference in Notification Activity Like this:
public static final String PREFS_NAME = "com.example.sociapp";
NotificationAdapter notificationAdapter1 = new NotificationAdapter(NotificationsActivity.this, NotificationList, NKeyList);
RnotificationList.setAdapter(notificationAdapter1);
isthereItem = notificationAdapter1.getItemCount();
Toast.makeText(NotificationsActivity.this, ""+isthereItem, Toast.LENGTH_SHORT).show();
//writing data into SharedPreference
SharedPreferences.Editor editor = settings.edit();
editor.putInt("changingicon",isthereItem);
//editor.commit();
editor.clear();
editor.apply();
And I am getting this int value in MainActivity Like this:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
// Reading from SharedPreferen
try {
//all I want to refresh below line everytime I start MainActivity.
int ChangeIcon = settings.getInt("changingicon", 0);
if (ChangeIcon == 0)
{
int valuebecomes = 0;
notificationIconSetting(valuebecomes);
}
else
{
int valuebecomes = 1;
notificationIconSetting(valuebecomes);
}
Toast.makeText(MainActivity.this, ""+ChangeIcon, Toast.LENGTH_SHORT).show();
}
catch (ClassCastException e){e.printStackTrace();}
The method I call, when I get int value from SharedPreference:
private void notificationIconSetting(int IconTochange)
{
if (IconTochange == 0) {
navigationView.getMenu().getItem(2).setIcon(R.drawable.notification);
}
else
{
navigationView.getMenu().getItem(2).setIcon(R.drawable.notificationalert);
navigationView.setItemIconTintList(null);
}
}
Actually I am getting an int value greater than 0 when there is a notification in the adapter, and when there is no notification in the adapter the int value is equal to 0, then I am using this value to change the notification icon.
When there is notification:
When there is no notification:
Now the problem is whenever I get a value, it remains the same until I clear app cache or Uninstall and then install again.
All I want to refresh the SharedPreference value every time I start MainActivity.
You want to remove one key/value from shared preference
here's how i do it.
public void clearSpecificKey(String key){
sharedPreferences.edit().remove(key).apply();
}
Few things to note :
You should create a generic class of Shared Preference Like below
public class SharedPrefs {
private static final String MY_PREFS_NAME = "YOUR-PREFERENCE-NAME";
private static SharedPreferences sharedPreferences;
private String masterKeyAlias;
public SharedPrefs(Context context) {
{
try {
masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
try {
sharedPreferences = EncryptedSharedPreferences.create(MY_PREFS_NAME,masterKeyAlias,context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
public String getStrings(Context mContext, String key){
return sharedPreferences.getString(key, null);
}
public void putString(Context mContext, String key, String value ){
sharedPreferences.edit().putString(key, value).apply();
}
public boolean getBoolean(Context mContext, String key){
return sharedPreferences.getBoolean(key, false);
}
public void putBoolean(Context mContext, String key, boolean value ){
sharedPreferences.edit().putBoolean(key, value).apply();
}
public static void clear(Context mContext){
sharedPreferences.edit().remove("user").apply();
}
public void clearSpecificKey(String key){
sharedPreferences.edit().remove(key).apply();
}
}
Here how to use it
Declaration :
SharedPrefs sharedPrefs;
Initialization :
sharedPrefs = new SharedPrefs(context);
just call the methods you want to use to store value in shared preference like
sharedPrefs.putString(context,key,value)
masterKeyAlias is to secure my Shared preferences.
Add this your app gradle
implementation "androidx.security:security-crypto:1.0.0-beta01"
you can read more about it here Best Practices
So, I've been saving some coordinates into a SharedPreferences, but when I try to get them back, the latitude returns fine like :44.374736436, but the longitude returns only 26, even though when I save it, I store it like: 26.24343343.
Where I save it:
PunctSalvat_SP punct = new PunctSalvat_SP(
String.valueOf(latitudine_start),
String.valueOf(longitudine_start),
id_alerta
);
SharedPrefManager.getInstance(getApplicationContext()).SalvarePunct(punct);
SharedPreferences.SalvarePunct():
public void SalvarePunct(PunctSalvat_SP punctSalvat) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_PUNCT, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY_latitudine, punctSalvat.getLatitudine());
editor.putString(KEY_longitudine, punctSalvat.getLongitudine());
editor.putString(KEY_id_marker, punctSalvat.getid());
editor.apply();
}
PunctSalvat_SP class:
public class PunctSalvat_SP {
private String latitudine, longitudine, id;
public PunctSalvat_SP(String latitudine, String longitudine, String id) {
this.latitudine = latitudine;
this.longitudine = longitudine;
this.id = id;
}
public String getLatitudine() {
return latitudine;
}
public String getLongitudine() {
return longitudine;
}
public String getid() {
return id;
}
}
Where I try to get it back:
if (SharedPrefManager.getInstance(this).ExistaPunct()) {
ArrayList<String> punct_ramas_in_memorie = new ArrayList<String>();
PunctSalvat_SP punct = SharedPrefManager.getInstance(this).getPunct();
punct_ramas_in_memorie.add(punct.getLatitudine());
punct_ramas_in_memorie.add(punct.getLongitudine());
ruta_pentru_o_problema_id.add(punct.getid());
CrearePunctDinRuta(punct_ramas_in_memorie);
}
SharedPreferences.ExistaPunct() and SharedPreferences.getPunct():
public boolean ExistaPunct() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_PUNCT, Context.MODE_PRIVATE);
return (sharedPreferences.getString(KEY_latitudine, null) != null && sharedPreferences.getString(KEY_longitudine, null) != null);
}
public PunctSalvat_SP getPunct() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_PUNCT, Context.MODE_PRIVATE);
return new PunctSalvat_SP(
sharedPreferences.getString(KEY_latitudine, null),
sharedPreferences.getString(KEY_longitudine, null),
sharedPreferences.getString(KEY_id_marker, null)
);
}
Debuggind the code, I observed the following:
When I save it, the punct has the right value (Ex: punct = (44.3432432423, 26.1323232, 26)), but when I try to get it back, the arraylist punct_ramas_in_memorie returns 2 elements, the 1st being the right latitude, but the 2nd one returns only 26, instead of 26.242423432.
Verify preference key values for KEY_longitudine and KEY_id_marker, if they are same.
If both key are same the value of id will overridden on longitude. and while retrieving value of longitude you will get value of id(what was written lastly on that key).
I'm trying to display a "rate us" dialog box the 5th time the user logs in to the app. On registering, the sharedpreference LOG_COUNT is set to 0 and the value of another shared prefernce LOG_BOOLEAN is set to true.
When the user logs in the first time, I check if the value of LOG_BOOLEAN is true. If it is, then the LOG_BOOLEAN is set to false. Every time the user logs in the value of the sharedpreference LOG_COUNT is increased. If it is 5, then I display the dialog box asking to rate and set it back to 0 if the user doesn't rate the app.
But every time the user logs in, the LOG_BOOLEAN is true and LOG_COUNTis 0 though I set it to false and increment it on the first login.
I use a class SessionManager to store and change sharedpreferences.
This is SessionManager.java:
package com.prematixsofs.taxiapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import java.util.HashMap;
/**
* Created by admin on 05-01-2016.
*/
public class SessionManager {
SharedPreferences pref;
String userName;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
int loginCount;
private static final String PREF_NAME = "TaxiPref";
private static String LOGIN_BOOLEAN = "loginBoolean";
private static String IS_LOGIN = "IsLoggedIn";
private static String LOG_COUNT = "loginCount";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
public static final String KEY_NAME = "name";
// Constructor
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(String name, String email) {
// Storing login value as TRUE
// Storing email in pref
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
editor.putBoolean(IS_LOGIN, true);
// commit changes
editor.commit();
}
public void setLoginCount(int count) {
if (count == 0) {
editor.putInt(LOG_COUNT, count);
editor.commit();
} else {
loginCount = pref.getInt(LOG_COUNT, 10);
editor.putInt(LOG_COUNT, loginCount + 1);
editor.commit();
}
}
public int getLoginCount() {
return pref.getInt(LOG_COUNT, 11);//random default value
}
public void setLoginSessionToTrue() {
editor.putInt(LOG_COUNT, 0);
editor.commit();
editor.putBoolean(LOGIN_BOOLEAN, true);
editor.commit();
}
public boolean getLoginBoolean() {
boolean bool;
bool = pref.getBoolean(LOGIN_BOOLEAN, true);
return bool;
}
public void setLoginBooleanToFalse() {
editor.putBoolean(LOGIN_BOOLEAN, false);
editor.putInt(LOG_COUNT, 0);
editor.commit();
boolean set = pref.getBoolean(LOGIN_BOOLEAN, false);
int cou = pref.getInt(LOG_COUNT, 100);
}
/**
* 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() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
*/
public String getUserName() {
HashMap<String, String> user = new HashMap<String, String>();
// user email id
return pref.getString(KEY_NAME, null);
}
public String getUserEmail() {
return pref.getString(KEY_EMAIL, null);
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Add new Flag to start new Activity
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* *
*/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
This is login:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//databaseHelper.delete();
item = databaseHelper.getLogin(uname.getText().toString(), pass.getText().toString());
if (item) {
sessionManager.createLoginSession(databaseHelper.getUserName(uname.getText().toString()), uname.getText().toString());
int c = sessionManager.getLoginCount(); // the value here is 11,the random default value.not the incremented value
countCheck = sessionManager.getLoginBoolean();
if (countCheck) { //check if first time log in
sessionManager.setLoginBooleanToFalse();
uname.setText("");
pass.setText("");
sessionManager.setLoginCount(0);
Intent intent2 = new Intent(getApplicationContext(), DateVehiclePicker.class);
startActivity(intent2);
} else if (sessionManager.getLoginCount() == 5) {
Intent intent1 = new Intent(getApplicationContext(), DateVehiclePicker.class);
sessionManager.setLoginCount(0);
intent1.putExtra("login", true);
startActivity(intent1);
}
} else
uname.setError("Enter a valid Email & Password");
}
});
This is Register.java where I set the sharedpreference to true and assign LOG_COUNTto zero:
signup.setOnClickListener(new View.OnClickListener() {
sessionManager.setLoginSessionToTrue();
});
try like this
private SharedPreferences.Editor getEditor() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
return settings.edit();
}
and then
public void setUserId(String userId) {
this.userId = userId;
getEditor().putString(userIdKey, userId).commit();
}
you should create default initialization
private void initSharedPreference() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
userId = settings.getString(userIdKey, ""); // to avoid nullpointerexception
}
call this method in you SharedPref constructor
EDIT
Create SharedPref like this:
public class SharedPref {
private Context mContext;
private String userId;
private final static String GENERAL_PREFERENCE = "general_pref";
private String userIdKey = "userIdKey";
public SharedPref(Context context) {
this.mContext = context;
initSharedPreference();
}
private void initSharedPreference() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
userId = settings.getString(userIdKey, "");
}
private SharedPreferences.Editor getEditor() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
return settings.edit();
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
getEditor().putString(userIdKey, userId).commit();
}
}
when create handler class:
public class DataSourceController {
public SharedPref sharedPref;
private static DataSourceController sInstance;
private DataSourceController(Context context) {
sharedPref = new SharedPref(context);
}
public static synchronized DataSourceController getInstance() {
return sInstance;
}
public static DataSourceController initSingleton(Context context) {
if (sInstance == null) {
sInstance = new DataSourceController(context);
}
return sInstance;
}
public static SharedPref getSharedPreference() {
return getInstance().sharedPref;
}
}
initialize this handler class in your Application class like this:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
DataSourceController.initSingleton(this);
}
}
so now you can call DataSourceController.getSharedPreference().getUserId(); and DataSourceController.getSharedPreference().setUserId("id"); from any place of your app.
Here is my Contacts activity (my main activity):
public class Contacts extends Delegate {
private static final String TAG = "Contacts";
public View listContactsView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("token", null);
if(restoredText == null)
{
Intent intent = new Intent(this, SignIn.class);
startActivity(intent);
}
setContentView(R.layout.activity_contacts);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ContactListFragment()).commit();
}
//new InEventAPI(this).execute("");
}
...
...
Here is my SignIn activity:
public SignIn extends Delegate {
...
...
public void personSignInDelegate(HttpResponse response, JSONObject result)
{
if(response != null && result != null)
{
switch(response.getStatusLine().getStatusCode())
{
case 200:
try {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("token", result.get("tokenID").toString());
editor.commit();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 401:
Toast.makeText(this, R.string.toastEmailPasswordIncorrect, Toast.LENGTH_LONG).show();
break;
}
}
else
{
Log.d(TAG, "Something went wrong!");
}
}
When I sign in, it commits on SharedPreferences, but when I close my app and re-open, the String becomes null and my OnCreate intents to SignIn again.
Is something that I'm missing?
Just to avoid doubts, my Delegate class:
public class Delegate extends ActionBarActivity {
protected InEventAPI api;
public Delegate() {}
public void personSignInDelegate(HttpResponse response, JSONObject result) {};
}
The problem is most likely with your use of getPreferences(). From the documentation:
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity. This simply calls the underlying
getSharedPreferences(String, int) method by passing in this activity's
class name as the preferences name.
Although both classes extend the Delegate class, they are both unique classes with unique names. This means that getPreferences() in Contacts returns a different SharedPreferenceObject compared to SignIn.
Either use getSharedPreferences(String, int)
Eg.
instead of
getPreferences(MODE_PRIVATE);
change it to
getSharedPreferences ("OneSharedPreference", MODE_PRIVATE);
or override getPreferences() in Delegate so it calls getSharedPreferences() with a unique name.
Alternatively, if you're not using the default SharedPreferences for anything (this is usually used by any PreferenceActivity classes), you can always call
PreferenceManager.getDefaultSharedPreferences() and pass in a Context instance.