I am developing an android application, In which I created one "SessionManager.java" which contains only static methods, in splash screen Activity only, I am creating the instance for "SessionManager ", Because it is the
fist activity in app, But in sometimes, I am getting null object reference ,
is it necessary to instantiate Class in every activity ?
Sample code
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public static void setLogin(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.commit();
Log.d(TAG, "User login session modified!");
}
public static void setMobile (String login_mobile) {
editor.putString("mobile", login_mobile);
editor.commit();
}
public static String getMobile() {
return pref.getString("mobile", "00");
}
}
sometimes in some activities , getMobile() method is returning null value, why ? can I check null value before return that ? please give me any suggestions, I stuck here.
If you are using it for storing values in shared preference then do it like this
public class AppSharedPreferences {
private SharedPreferences appSharedPrefs;
private SharedPreferences.Editor prefsEditor;
private static AppSharedPreferences appSharedPrefrence;
public AppSharedPreferences(Context context) {
this.appSharedPrefs = context.getSharedPreferences("sharedpref", Context.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public AppSharedPreferences() {
}
public static AppSharedPreferences getsharedprefInstance(Context con) {
if (appSharedPrefrence == null)
appSharedPrefrence = new AppSharedPreferences(con);
return appSharedPrefrence;
}
public SharedPreferences getAppSharedPrefs() {
return appSharedPrefs;
}
public void setAppSharedPrefs(SharedPreferences appSharedPrefs) {
this.appSharedPrefs = appSharedPrefs;
}
public SharedPreferences.Editor getPrefsEditor() {
return prefsEditor;
}
public void Commit() {
prefsEditor.commit();
}
public void clearallSharedPrefernce() {
prefsEditor.clear();
prefsEditor.commit();
}
public void setUserId(String userid)
{
this.prefsEditor=appSharedPrefs.edit();
prefsEditor.putString("user_id", userid);
prefsEditor.apply();
}
public String getUserId() {
return appSharedPrefs.getString("user_id","");
}
}
and then to use it in class do it like this way
appSharedPreferences=AppSharedPreferences.getsharedprefInstance(ActivityLogin.this);
and then call your method using appsharedPreferences.yourMethod();
Related
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();
I have been searching for the correct answer everywhere, but couldn't find it anywhere. That is why I am posting this question, this may look very similar to other questions but I didn't find the answer to this yet. I have to retrieve the user data that was saved during the login on Android device and I want to use the same data in a fragment, I tried using several answers found on StackOverflow, none of them worked for me. Look at the code below, how can I get the user values into strings?
SharedPreferences preferences = getActivity().getSharedPreferences("mysharedpref",Context.MODE_PRIVATE);
String user_name = preferences.getString("user_id",null);
String password = preferences.getString("role", null);
I have to pass these string values to a URL, but it doesn't work. I also checked passing values manually, it's working. For example, if I take assign values to the above strings like
String user_name="admin";
String password="administrator";
Best way to use your SharedPrefernce is by using your appContext that is accessible to the whole App(Common SharedPrefernce and accessible Everywhere).
Define your SharedPrefernce instance in your Application class with get and set methods as below : (If you have not created the Application class then create one as below, This class is called at the start of your app)
public class Application extends android.app.Application {
private static Application _instance;
private static SharedPreferences _preferences;
#Override
public void onCreate() {
super.onCreate();
_instance = this;
}
public static Application get() {
return _instance;
}
/**
* Gets shared preferences.
*
* #return the shared preferences
*/
public static SharedPreferences getSharedPreferences() {
if (_preferences == null)
_preferences = PreferenceManager.getDefaultSharedPreferences(_instance);
return _preferences;
}
//set methods
public static void setPreferences(String key, String value) {
getSharedPreferences().edit().putString(key, value).commit();
}
public static void setPreferences(String key, long value) {
getSharedPreferences().edit().putLong(key, value).commit();
}
public static void setPreferences(String key, int value) {
getSharedPreferences().edit().putInt(key, value).commit();
}
public static void setPreferencesBoolean(String key, boolean value) {
getSharedPreferences().edit().putBoolean(key, value).commit();
}
//get methods
public static String getPrefranceData(String key) {
return getSharedPreferences().getString(key, "");
}
public static int getPrefranceDataInt(String key) {
return getSharedPreferences().getInt(key, 0);
}
public static boolean getPrefranceDataBoolean(String key) {
return getSharedPreferences().getBoolean(key, false);
}
public static long getPrefranceDataLong(String interval) {
return getSharedPreferences().getLong(interval, 0);
}
}
Declare the Application class in AndroidManifest.xml file with line android:name=".Application" as shown in below snippet:
<application
android:name=".Application"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme">
Now, How to store key-value:
Application.setPreferences("Key","String_Value");
How to fetch key-value:
String value_string=Application.getPrefranceData("Key");
You can now set-SharedPrefernce key-value and get-SharedPrefernce value from anywhere in the app using public Application class and the static get and set methods
Firstly create a SharedPreference.java Class.
public class SharedPreference {
Context context;
SharedPreferences sharedPreferences;
String user_name;
String password;
public SharedPreference(Context co) {
context = co;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public String getPassword() {
password = getStringInput("password");
return password;
}
public void setPassword(String password) {
this.password = password;
stringInput("password", password);
}
public String getUser_name() {
user_name = getStringInput("Username");
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
stringInput("Username", user_name);
}
public void stringInput(String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public String getStringInput(String key) {
return sharedPreferences.getString(key, "0");
}
}
Now go into activity or Fragment
example: I'm gone use it in MainActivity.java
public class MainActivity extends AppCompatActivity {
Prefrences prefrences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Dashboard");
prefrences = new Prefrences(MainActivity.this);
prefrences.setUser_name("Rishabh Jain");
prefrences.setUser_name("8369554235");
Log.e("Details",prefrences.getUser_name()+" "+prefrences.getPassword())
}
}
The output will be Rishabh Jain 8369554235.
Similarly, you can use this in any Activity or any Fragment
I guess you are trying to get values with different key. Get values with same key you put them with.
String user_name = preferences.getString(preferences.KEY_USERNAME,null);
String password = preferences.getString(preferences.KEY_PASSWORD, null);
----BUT----
And don't use singleton pattern for SharedPreferences it is very bad to use Context in singleton. It will crash your app. You can figure it out why.
Instead use static methods.
public class PreferenceUtil {
public static final String PASSWORD = "PASSWORD";
public static void setInt(Context context, int in, String key) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
editor.putInt(key, in);
editor.apply();
}
public static int getInt(Context context, String key) {
SharedPreferences settings;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(key)) {
return settings.getInt(key, 0);
} else
return 0;
}
}
And access it like this
int password = PreferenceUtil.getInt(getActivity(), PreferenceUtil.PASSWORD);
I developing an app which may often use ability to store/get some pair/value data in any app place such as an activity or it fragments. I decided use for it singleton. Is my class coded in right way?
public class StorageManager {
private static StorageManager instance;
public static final String PREF_NAME = "app_settings";
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
public static StorageManager getInstance(Context context) {
if(instance == null)
instance = new StorageManager(context.getApplicationContext());
return instance;
}
private StorageManager(Context context) {
preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
editor = preferences.edit();
}
public void setUserEmail(String token)
{
editor.putString("email", token);
editor.commit();
}
public String getUserEmail()
{
return preferences.getString("email", "");
}
}
Another clean way to achieve the same :)
public enum AppSharedPref {
instance;
SharedPreferences sharedPreferences;
// setter of the property.
public void setWeatherUpadte(int value) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext());
sharedPreferences.edit().putInt("Weather", value).apply();
}
// getter of the property.
public int getWeatherUpadte() {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext());
return sharedPreferences.getInt("Weather", 0);
}
}
Simply access the property with :
AppSharedPref.instance.getWeatherUpadte();
Simple and Easy way to use SharedPrefrences
public class User {
SharedPreferences sharedPreferences;
public String getEnroll() {
enroll=sharedPreferences.getString("userdata","");
return enroll;
}
public void setEnroll(String enroll) {
this.enroll = enroll;
sharedPreferences.edit().putString("userdata",enroll).commit();
}
public void remove(){
sharedPreferences.edit().clear().commit();
}
String enroll;
Context context;
public User(Context context){
this.context=context;
sharedPreferences=context.getSharedPreferences("userinfo",Context.MODE_PRIVATE);
}
}
Create a user class and call it whenever you want to save the user login session
edt_enroll_login=(EditText)findViewById(R.id.edt_roll_login);
user_roll = edt_enroll_login.getText().toString().trim();
User user=new User(LOGIN.this);//pass the context to user class
user.setEnroll(user_roll);//save user session(here by enrollment number) in userinfo.xml file
Here i used login.java file to call user class
Just create User class object to check and remove userdata(session) -User user=new User(yourcallingactivity.this);
And to check if user is already login use user.getEnroll() method of user class,if user is already login then jump to home activity for user
For removing the session of user after logout use user.remove() method of user class.
Edit: this code actually works. I had problem in the code that used it. Leaving it anyway in case anybody will find it useful.
I have a class with two methods to write and read a boolean persisted preference. However, if I write a new value and then try to read it, I still get the old value. Only if I kill the app and relaunch it, I do get the new value. Any idea what the problem is?
Context mContext;
....
public void writeFlag(boolean flag) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mContext);
Editor editor = sharedPreferences.edit();
editor.putBoolean("mykey", flag);
editor.commit();
}
public boolean readFlag() {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(mContext);
return sharedPreferences.getBoolean("mykey", false);
}
public static boolean getBooleanFromSP(String key) {
// TODO Auto-generated method stub
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}//getPWDFromSP()
public static void saveBooleanInSP(String key, boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}//savePWDInSP()
public static boolean getBooleanFromSP(String key) {
// TODO Auto-generated method stub
SharedPreferences preferences =
getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ",
android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}//getPWDFromSP()
public static void saveBooleanInSP(String key, boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}//savePWDInSP()
public class SharePref {
private static final String TAG = SharePref.class.getSimpleName();
private static SharePref mThis;
private Context mContext;
private SharedPreferences mPreference;
private SharePref() {
}
public static void init(Context context) {
if (mThis == null) {
mThis = new SharePref();
mThis.setData(context);
}
}
private void setData(Context context) {
mThis.mContext = context;
mPreference = mContext.getSharedPreferences(TAG, Context.MODE_PRIVATE);
}
public static SharePref getInstance() {
return mThis;
}
public void writeString(String tag, String data) {
SharedPreferences.Editor editor = mPreference.edit();
editor.putString(tag, data).apply();
}
public String readString(String tag) {
if (mPreference == null)
mPreference = mContext.getSharedPreferences(TAG, Context.MODE_PRIVATE);
return mPreference.getString(tag, null);
}
public void writeBoolean(String tag, boolean data) {
SharedPreferences.Editor editor = mPreference.edit();
editor.putBoolean(tag, data).apply();
}
public boolean readBoolean(String tag) {
return mPreference.getBoolean(tag, false);
}
public void clear(String tag) {
mPreference.edit().remove(tag).apply();
}
}
//In Activity
SharePref.init(this);
SharePref.getInstance().writeString("key","value");
I have a SharedPreferences that currently works in one class but doesn't work in a second class. I think I might be calling it wrong, because the error I get says:
The method getSharedPreferences(String, int) is undefined for the type CheckPreferences
The code that works correctly with the SharedPrefernces is this:
public void loadApp()
{
setContentView(shc_BalloonSat.namespace.R.layout.main);
alert = new AlertDialog.Builder(this).create();
//String returned = "";
lastpacketsPHP = "";
pref = getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
//prefEditor.putString(lastpacketsPHP, "/* Insert PHP file location here */");
//prefEditor.commit();
// These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly.
prefEditor.putString(lastpacketsPHP, "/* Insert PHP file location here */");
prefEditor.commit();
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
api = new httpAPI(this);
map = new mapAPI(this);
dialog = new runDialog(this, api, new runDialog.OnDataLoadedListener()
{
public void dataLoaded(String textViewString)
{
infoTV = (TextView)findViewById(shc_BalloonSat.namespace.R.id.info);
infoTV.setText(textViewString);
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
});
dialog.execute();
}
CheckPreferences cp = new CheckPreferences(this, new CheckPreferences.CheckPreferencesListener()
{
public void onSettingsSaved()
{
// This function let's the activity know that the user has saved their preferences and
// that the rest of the app should be now be shown.
check.saveSettings();
}
public void onCancel()
{
Toast.makeText(getApplicationContext(), "Settings dialog cancelled", Toast.LENGTH_LONG).show();
}
});
cp.show();
}
In my other class, I don't know if I'm just calling it incorrectly or if I'm looking at it completely incorrectly. The class is shown below:
package shc_BalloonSat.namespace;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.CheckBox;
public class CheckPreferences extends Dialog
{
Context shc;
private CheckBox altitudeCheckBox = (CheckBox) findViewById(R.id.altitudeCheckbox);
private CheckBox latitudeCheckbox = (CheckBox) findViewById(R.id.latitudeCheckbox);
private CheckBox longitudeCheckbox = (CheckBox) findViewById(R.id.longitudeCheckbox);
private CheckBox velocityCheckbox = (CheckBox) findViewById(R.id.velocityCheckbox);
private CheckPreferencesListener listener;
SharedPreferences pref;
Editor prefEditor;
String userAltitudePreference;
String userLatitudePreference;
String userLongitudePreference;
String userVelocityPreference;
String userAltitudeChoice;
String userLatitudeChoice;
String userLongitudeChoice;
String userVelocityChoice;
public interface CheckPreferencesListener
{
public void onSettingsSaved();
public void onCancel();
}
public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
this.setContentView(R.layout.custompreferences);
this.setCancelable(false);
this.setCanceledOnTouchOutside(false);
this.setTitle("Data View Settings");
pref = getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
initOnClick();
}
private void initOnClick()
{
View.OnClickListener click = new View.OnClickListener()
{
public void onClick(View v)
{
switch (v.getId())
{
case R.id.saveBtn:
{
saveSettings();
listener.onSettingsSaved();
dismiss();
break;
}
case R.id.cancelBtn:
{
listener.onCancel();
dismiss();
break;
}
}
}
};
// Save Button
this.findViewById(R.id.saveBtn).setOnClickListener(click);
// Cancel Button
this.findViewById(R.id.cancelBtn).setOnClickListener(click);
}
public void saveSettings()
{
// This function is called when the user chooses the save their preferences
if (altitudeCheckBox.isChecked())
{
userAltitudeChoice = "true";
prefEditor.putString(userAltitudePreference, userAltitudeChoice);
prefEditor.commit();
}
else if (latitudeCheckbox.isChecked())
{
userLatitudeChoice = "true";
prefEditor.putString(userLatitudePreference, userLatitudeChoice);
prefEditor.commit();
}
else if (longitudeCheckbox.isChecked())
{
userLongitudeChoice = "true";
prefEditor.putString(userLongitudePreference, userLongitudeChoice);
prefEditor.commit();
}
else if (velocityCheckbox.isChecked())
{
userVelocityChoice = "true";
prefEditor.putString(userVelocityPreference, userVelocityChoice);
prefEditor.commit();
}
else
{
}
}
}
The error I mentioned above occurs on this line:
pref = getSharedPreferences("shared_prefs", 1);
Any help will be greatly appreciated. I'd love to know what I'm doing wrong.
Ofcourse SharedPreferences is same across multiple classes. It allows you to save and retrieve persistent key-value pairs of primitive data types in your application.
Standard practice is to have one single Helper class with all static methods to save and retrieve key-value pairs of each type. Also, have all your keys in one static class SharedPreferenceKeys. It avoids silly typographical mistakes. Following is sample class which you can use:
package com.mobisys.android;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
public class HelperSharedPreferences {
public static class SharedPreferencesKeys{
public static final String key1="key1";
public static final String key2="key2";
}
public static void putSharedPreferencesInt(Context context, String key, int value){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putInt(key, value);
edit.commit();
}
public static void putSharedPreferencesBoolean(Context context, String key, boolean val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putBoolean(key, val);
edit.commit();
}
public static void putSharedPreferencesString(Context context, String key, String val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putString(key, val);
edit.commit();
}
public static void putSharedPreferencesFloat(Context context, String key, float val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putFloat(key, val);
edit.commit();
}
public static void putSharedPreferencesLong(Context context, String key, long val){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=preferences.edit();
edit.putLong(key, val);
edit.commit();
}
public static long getSharedPreferencesLong(Context context, String key, long _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getLong(key, _default);
}
public static float getSharedPreferencesFloat(Context context, String key, float _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getFloat(key, _default);
}
public static String getSharedPreferencesString(Context context, String key, String _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, _default);
}
public static int getSharedPreferencesInt(Context context, String key, int _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getInt(key, _default);
}
public static boolean getSharedPreferencesBoolean(Context context, String key, boolean _default){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(key, _default);
}
}
To put value (say boolean), call following from activity:
HelperSharedPreferences.putSharedPreferenceBoolean(getApplicationContext(),HelperSharedPreferences.SharedPreferenceKeys.key1, true);
To get same value, call following:
HelperSharedPreferences.getSharedPreferenceBoolean(getApplicationContext(),HelperSharedPreferences.SharedPreferenceKeys.key1, true);
Last value is default value.
You should have to call this method via context reference variable.
public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
shc=context;
...
pref = shc.getSharedPreferences("shared_prefs", 1);
...
}
The Dialog class doesn't have a getSharedPreferences method defined. You probably want:
getContext().getSharedPreferences(...)