I create a shared preferences file at login, but I cannot figure out the code to change the preferences inside of my app.
SharedPreferences.java
public void editHospitalId(String hospital_id) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context);
Editor editor = prefs.edit();
editor.putString(KEY_HOSPITALID, hospital_id);
editor.commit();
}
I have already initialized a value for KEY_HOSPITALID on login:
SharedPreferences.java
// 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 name, String hospital_id){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_HOSPITALID, hospital_id);
// commit changes
editor.commit();
I suppose I could delete the value and re-add it? But there has to be a way to overwrite it.
SharedPreferences contain data as key-value pairs, so calling putString(KEY, VALUE) will assign VALUE to the KEY, regardless of if it's already set. In short, it deletes previous entry automatically.
Related
I am trying to save a boolean into shared preferences with a value of true but when I log it I keeping seeing it returning a false value. Please see the code below and also bear in mind that this code is within a fragment.
SharedPreferences AppPreferences = getActivity().getSharedPreferences("myPrefs", Activity.MODE_PRIVATE);
boolean propertyManagerLoggedIn = AppPreferences.getBoolean(PROPERTYMANAGER_LOGGEDIN, false);
if(!propertyManagerLoggedIn)
{
SharedPreferences.Editor editor = AppPreferences.edit();
transitionInterface.showDashboardIcons();
AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
editor.commit();
//boolean vlaue = prefs.getbooleanflag(context, false);
Log.d("tag",""+propertyManagerLoggedIn);
}
else
{
Log.d("tag",""+propertyManagerLoggedIn);
}
and below is the relevant lines of code from my AppPreferences class
public final static String PROPERTYMANAGER_LOGGEDIN = "PROPERTYMANAGER_LOGGEDIN";
public static boolean propertyManagerLoggedn(Context context)
{
TinyDB settings = new TinyDB(context);
return settings.getBoolean(AppPreferences.PROPERTYMANAGER_LOGGEDIN);
}
every time you call edit() a new Editor is being returned to you. Accordingly to the documentation
Create a new Editor for these preferences, through which you can make
modifications to the data in the preferences and atomically commit
those changes back to the SharedPreferences object.
so you can either do
AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true).commit();
or
editor.putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
editor.commit();
but calling putBoolean on an instance and commit on an other won't probably help
You are calling commit on a different instance.
Basically AppPreferences.edit() will give you a new instance.
AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
This is another instance in which you are putting the boolean value.
Use the same instance which you have created.
Your code should look like this:
SharedPreferences.Editor editor = AppPreferences.edit();
transitionInterface.showDashboardIcons();
editor.putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
editor.commit();
I'm trying to code global method by extending the Application class.
Specifically I'm trying to add 2 method to rapidly access one value that is stored in the SharedPreferences.
Unfortunately I can't make the SharedPreferences work, here is the code:
package postfixcalculator.mattiarubini.com.postfixcalculator;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
public class PostfixCalculatorExtendApplication extends Application {
public void ChangePreference (boolean flag){
//I'm updating the preference file based on the purchase
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(getString(R.string.purchase_status), flag);
editor.commit();
}
public boolean RetrievePreferences (){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
/*If the file doesn't exist, I create the file and I'm returned with a false value.
* Because if the file was not created it's likely to be the first install.
* If the user acquired the product on the store, it will be able to restore its purchase.*/
boolean flagPurchase = sharedPref.getBoolean(getString(R.string.purchase_status), false);
return flagPurchase;
}
}
I understand that getActivity() doesn't work in an Activity but in a Fragment, I just don't know what to do in this specific case.
Usually in the Activity, to make SharedPreferences works, I just need to use the key word this.
These are the errors I get:
Cannot resolve method 'getActivity()'
Cannot resolve method 'getPreferences(int)'
try getApplicationContext() with getSharedPreferences()
Use
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences .edit();
editor.putBoolean(getString(R.string.purchase_status), flag);
editor.commit();
I use getSharedPreferences("Name of preferences", Context.MODE_PRIVATE); in my Application class.
Try using getApplicationContext() instead of getActivity().
Try this for saving shared Preferences:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.edit().putString("key","value").apply();
For getting shared preferences value:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.getString("key","");
I hope this will help.
Here's what I have done.
public void addToFavorites2(View view) {
//ImageButton button = (ImageButton)findViewById(R.id.imageButton);
//button.setImageResource(R.mipmap.star_clicked_button);
int movieId = favoriteMovieId;
SharedPreferences settings = getSharedPreferences("FavoritesIdKey", MODE_PRIVATE);
Log.v("tessssst", String.valueOf(settings.contains(favoriteMovieTitle)));
SharedPreferences.Editor editor = settings.edit();
editor.putString(favoriteMovieTitle, String.valueOf(movieId));
editor.commit();
}
public boolean movieIsInFavorites()
{
Log.v("method check","is working");
SharedPreferences settings = getSharedPreferences("FavoritesIdKey", MODE_PRIVATE);
Log.v("tezzzzzt", String.valueOf(settings.contains(favoriteMovieTitle)));
if(settings.contains(String.valueOf(favoriteMovieId)))
{
Log.v("truth test","true");
return true;
}
Log.v("truth test","false");
return false;
}
In the given code I have created two methods. in the first method when I call
SharedPreferences settings = getSharedPreferences("FavoritesIdKey", MODE_PRIVATE);
settings.contains(FavoriteMovieTitle);
the data is found and returns true.
when I call the same
SharedPreferences settings = getSharedPreferences("FavoritesIdKey", MODE_PRIVATE);
settings.contains(FavoriteMovieTitle);
In the second method, it does not return true. is there a fundamental thing about shared preferences that I am missing? if more information is needed i apologize. both methods are next to each other without anything between them.
edit- I will add that the first method is called when i press a button on the details screen(details screen is already finished setup and showing).
the second method i was calling in the onCreateView attempting to check if the movie is already in the favorites list apon start up.
The first method is called when you press a button and the second method is called in the onCreateView. So the second method is called before the first method. However, you insert favoriteMovieTitle into xml in the first method so when the second method was called, favoriteMovieTitle had not been in xml and it would return false.
To Store/Obtain shared preferences, use the following method In your activity
SharedPreferences settings = this.getSharedPreferences("FavoritesIdKey",
Context.MODE_PRIVATE);
To store value in SharedPreferences
SharedPreferences.Editor editor = settings.edit();
editor.putString(favoriteMovieTitle, String.valueOf(movieId));
To read SharedPreferences in other class write this line if same class
then no need to write this direct use getString
SharedPreferences settings = this.getSharedPreferences("FavoritesIdKey",
Context.MODE_PRIVATE);
If your are in same class the above line not need to write again.
String myvalueInPref = settings.getString(favoriteMovieTitle, "defaultValue");
I have two different app,i have user database in backend,if any user loged in one app,he can also login in the another app without pressing login,just like facebook,how can i implement SSO in app?
You can do that using Content Provider also you can do the same using Shared preferences
Using Shared preferences here is the example:
Call this method when user logged in one app.
public void writeSSOInfo(){
SharedPreferences prefs = getSharedPreferences("CheckSSO",Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = prefs.edit();
if(userLoggedIn){
editor.putBoolean("isLoggedIn", true);
}else{
editor.putBoolean("isLoggedIn", false);
}
editor.commit();
}
After saving in shared memory you can access the same detail in another application using below method.
public void readSSOInfo(){
Context con;
try {
con = createPackageContext("com.app.packagename1", 0);
SharedPreferences pref = con.getSharedPreferences("CheckSSO", Context.MODE_PRIVATE);
dataShared = pref.getBoolean("isLoggedIn", false);
}
catch (Exception e) {
Log.e("Not data shared", e.toString());
}
}
My advice would be after you logged in with any of the apps, I would store a user token with in SharedPreferences between both apps. Then get it at onCreate method of the both apps like this:
String PACKAGE_NAME = "your.package";
String PREFERENCE_NAME = "user-token";
String USER_TOKEN = "";
try {
myContext = createPackageContext(PACKAGE_NAME,Context.MODE_WORLD_WRITEABLE);
SharedPreferences sharedPrefs = myContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_WORLD_READABLE);
USER_TOKEN = sharedPrefs.getString(PREFERENCE_NAME, "");
}
catch (NameNotFoundException e) {
e.printStackTrace();
}
Then check if USER_TOKEN is empty or not and if it is not I would skip to next screen and keep using same Auth token.
I managed to integrate twitter digits and the authentication is working, but I want to check if the user already added his number and code.
For now I only have the authentication part:
final TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Crashlytics(), new Twitter(authConfig));
And the button event:
digitsButton = (DigitsAuthButton) findViewById(R.id.auth_button);
digitsButton.setCallback(new AuthCallback() {
#Override
public void success(DigitsSession session,
String phoneNumber) {
// Do something with the session
Toast.makeText(WelcomeActivity.this,"Registration Successful",Toast.LENGTH_SHORT).show();
}
#Override
public void failure(DigitsException exception) {
// Do something on failure
Toast.makeText(WelcomeActivity.this,"Registration Failed",Toast.LENGTH_SHORT).show();
}
});
-
How can I check if the user already made these steps?
You can save the fact that an authentication was successful by storing the data somewhere. Storage Options
Using SharedPreferences, to check if an authentication was successful you would use isAuthenticated below:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean isAuthenticated = settings.getBoolean("ALREADY_AUTHENTICATED", false);
And to set that an authentication was successful (true), you could put this in the callback's success method
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("ALREADY_AUTHENTICATED", true /** or false */);
// Commit the edits!
editor.commit();