How do I make a shared library for SharedPreference? - android

I am working on an application that has a lot of modules in it, and I need to load data from a SharedPreference class that I made called SharedPrefManager in the :app application which is the application where I implement the other modules into a module called :mediplan where I just want to retrieve the ID that I saved in the SharedPrefManager.
I tried to implement the dependency in the module in question :mediplan but I ended up with a lot of errors so I went back and took off the dependency.
The SharedPrefManager class:
package com.example.tuteur;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class SharedPrefManager {
private static final String SHARED_PREF_NAME = "CIN";
private static final String IDCONT = "con";
private static final String malade = "malade";
private static SharedPrefManager mInstance;
private static Context ctx;
public SharedPrefManager(Context context) {
ctx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
public void setIdCont(String id) {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(IDCONT, id);
editor.apply();
}
//this method will give the logged in user
public String getIdCont() {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(IDCONT, null);
}
//this method will give the logged in user
public void setMalade(String malade) {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(malade, malade);
editor.apply();
}
//this method will give the logged in user
public String getMalade() {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(malade, null);
}
//this method will log the user out
public void logout() {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
}

the solution I found is to use put extras and put bundle instead of using the shared libraries

Related

My preference become null after I try to hot restart or reopening an app

Is it normal for shared preference reset the value after I try to hot restart or reopening an app ? because my preference become null after I do that.
Thank you.
i fix this problem by remove this line from my app :
SharedPreferences.setMockInitialValues({});
void main() {
// ignore: invalid_use_of_visible_for_testing_member
SharedPreferences.setMockInitialValues({});
runApp(MyApp());
}
I hope this will work for you.
Make Singleton class of SharedPreference
public class SessionManager {
public SharedPreferences prefs;
private Context _Context;
private SharedPreferences.Editor editor;
private static final String PREF_NAME = "YourAppName";
private static final int PREF_MODE = 0;
public SessionManager(Context context) {
if (context != null) {
this._Context = context;
prefs = context.getSharedPreferences(PREF_NAME, PREF_MODE);
editor = prefs.edit();
}
}
public static final String KEY_NAME = "name";
public void setKeyUserName(String name) {
editor.putString(KEY_NAME, name);
editor.commit();
}
public String getKeyUserName() {
return prefs.getString(KEY_NAME, null);
}
}
How to use: In Activity / Fragment
public SessionManager sessionManager;
sessionManager = new SessionManager(YourActivityContext);
For Saving data:
sessionManager.setKeyUserName("Your Value");
For getting Data:
sessionManager.getKeyUserName();

JSONObject string is not stored in sharedpreferences

I am passing a jsonobject string value to my shared preferences and commiting it. But while fetching this, its returning the default value.
For putting :
public void new_putMultipleProfileData(String got_multiple_json_data){
Editor editor=app_prefs.edit();
editor.putString(NEW_TESTING_PIC_ID, got_multiple_json_data);
editor.commit();
}
For getting :
public String new_getMultipleProfileData(){
return app_prefs.getString(NEW_TESTING_PIC_ID,"0");
}
Complete Preference Helper Class :
public class PreferenceHelper {
private final String PREF_NAME = "Testing_xyz";
private SharedPreferences app_prefs;
//For Testing
public static final String NEW_TESTING_PIC_ID = "testing";
private Context context;
public PreferenceHelper(Context context) {
app_prefs = context.getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
this.context = context;
}
public void new_putMultipleProfileData(String got_multiple_json_data){
AppLog.Log("new_data_80503","got_multiple_json_data "+got_multiple_json_data);
Editor editor=app_prefs.edit();
editor.putString(NEW_TESTING_PIC_ID, "hello");
editor.commit();
}
public String new_getMultipleProfileData(){
AppLog.Log("new_data_80503","new_getMultipleProfileData "+app_prefs.getString(NEW_TESTING_PIC_ID,"0"));
return app_prefs.getString(NEW_TESTING_PIC_ID,"0");
}
}
If you want to use same preference manager across the app then use defaultSharedPreference. getSharedPreferences return preference file for that context only, it is different for different context.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
or
you can use ApplicationContext instead of context

Shared Preferences not working

I have a problem where my shared preferences are not working in a class file.I am confused and not able to solve it.Below is my file globalfile which saves data as follows.
public class globalfile extends Activity {
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
public static final String Pwd = "pwdKey";
public static final String Email = "emailKey";
private static String global_username = "null/", global_pwd = "null/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
}
public String getusername() {
global_username = sharedpreferences.getString(Email, "");
return global_username;
}
public String getuserpwd() {
global_pwd = sharedpreferences.getString(Pwd, "");
return global_pwd;
}
public void setusername(String someVariable) {
global_username = someVariable;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Email,global_username);
editor.commit();
}
public void setuserpwd(String someVariable) {
global_pwd = someVariable;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Pwd,global_pwd);
editor.commit();
}
}
I first called setuserpwd() & setusername() then getuserpwd() & getusername() from another activity using object of class globalfile.But always returns null.although if I use this code without shared pref.it is working fine
create an instance of Activity with Activity class object
Technically, you can create an instance of an Activity class. but, activity instance would be useless because its underlying Context would not have been set up.
The rule is that you should never ever create instances of Android components (Activity, Service, BroadcastReceiver, Provider) yourself (using the new keyword or other means). These classes should only ever be created by the Android framework, because Android sets up the underlying Context for these objects and also manages the lifecycle.
I think your newly created activity object can't get actual context. so try to avoid your current flow. I suggest you to create a separate class that may use as factory class and I think your problem will solved.
Or another solution would be like this :
Context context = /*get application context*/
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
/*get value from this sharedPref*/
So you don't need to create activity class object and here you should avoid your previous getter method to get value.
change you globalfile to be a utility class and not an activity so it can be used really easily by other parts of your app (that aren't an activity but have access to an android context).
public class Global {
private final SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
public static final String Pwd = "pwdKey";
public static final String Email = "emailKey";
private static String global_username = "null/",
global_pwd = "null/";
public Global(Context context) {
this.sharedpreferences = context.getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
}
public String getusername() {
global_username = sharedpreferences.getString(Email, "null/");
return global_username;
}
public String getuserpwd() {
global_pwd = sharedpreferences.getString(Pwd, "null/");
return global_pwd;
}
public void setusername(String someVariable) {
global_username = someVariable;
sharedpreferences.edit().putString(Email,global_username).commit();
}
public void setuserpwd(String someVariable) {
global_pwd = someVariable;
sharedpreferences.edit().putString(Pwd,global_pwd).commit();
}
}
And here's how to use your new util class
Global global = new Global(context);
global.setusername("foo");
Log.d("TAG", "username from prefs = " + global.getusername());
global.setuserpwd("bar");
Log.d("TAG", "password from prefs = " + global.getusername());

Android save and read values from SharedPreferences

How to save values in preferences (and read) with quite compact way without creating several instances - i want be sure that i have only one instance of pref
A SharedPreferences object is a natural singleton. Your first call to read in a SharedPreferences (e.g., PreferenceManager.getDefaultSharedPreferences()) will create it. Second and subsequent calls within the same process will return that same instance. Hence, so long as you are consistent about where you get your SharedPreferences from, you will only ever have one instance (at most) in your process.
CommonsWare is right, but as i understood, you want somehow to structure you job with Preferences, i use singleton for this, something like this:
public class Preferences {
private static final String USERNAME = "username";
private static final String LOG_TAG = Preferences.class.getSimpleName();
private static Preferences sInstance;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private Context mContext;
private Preferences(Context context) {
mContext = context;
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
mEditor = mSharedPreferences.edit();
}
public static Preferences getInstance(Context context) {
if (sInstance == null) {
sInstance = new Preferences(context);
}
return sInstance;
}
public void setUsername(String username) {
mEditor.putString(USERNAME, username);
commit();
}
public String getUsername() {
return mSharedPreferences.getString(USERNAME, null);
}
public boolean commit() {
return mEditor.commit();
}
}
And where it is necessary write
Preferences.getInstance(this).setUsername("USERNAME");
and read
Preferences.getInstance(this).getUsername();

Can I put SharedPreferences.edit() in the constructor of my class or it needs to be called everytime the preferences change and get committed?

Do I need to call edit SharedPreferences everytime before I change the preferences and commit or can I do that just once in the costructor?
Is this correct ?
public class MyPreferencesClass {
private Context ctx;
private static SharedPreferences settings;
private static SharedPreferences.Editor editor;
// Constructor Class //
public MyPreferencesClass(Context context) {
this.ctx = context;
settings = ctx.getSharedPreferences(CUSTOM_PREFS_NAME, 0);
editor = settings.edit(); // Called Only once in constructor not not everytime in edit methods
}
public static void setSomePref1(Boolean boolValue) {
// editor = settings.edit(); Not required everytime
editor.putBoolean(PREFS_1, boolValue);
editor.commit();
}
public static void setSomePref2(Boolean boolValue) {
editor.putBoolean(PREFS_2, boolValue);
editor.commit();
}
...
}
you should be able to use SharedPreferences.Editor instance as long as it's valid so no need to call SharedPreferences#edit() every time.

Categories

Resources