SharedPreferences in non activity class NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to use SharedPreferences in a non activity class from onResume() in an activity but I'm getting a NullPointerException on the context.
For some reason I cannot get the context in onResume(). Not sure if I'm missing something, but any help would be appreciated.
onResume() Method in my activity
#Override
protected void onResume() {
super.onResume();
// The activity has become visible (it is now "resumed").
// Check User's Access Token exists and hasn't expired.
AccountFunctions accountFunctions = new AccountFunctions();
if (!accountFunctions.validateUserToken(this)) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
validateUserToken(Context context) method in AccountFunctions Class
public Boolean validateUserToken(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
String accessToken = sharedPref.getString(getString(R.string.user_access_token), null);
DateTime expiryDate = new DateTime(sharedPref.getLong(getString(R.string.user_expires), 0));
if (accessToken == null || expiryDate.isBeforeNow()) {
return false;
} else {
return true;
}
}
The Error
java.lang.RuntimeException: Unable to resume activity
{uk.co.itsstonbury.www.intouch/uk.co.itsstonbury.www.intouch.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.Context
android.content.Context.getApplicationContext()' on a null object
reference

replace getString(R.str with context.getString because AccountFunctions class has not been created by the OS so it doesn't have it's own context ready.
Basically activity gets it's context form application when oncreate function get called by OS callbacks since it's not gonna happen in this case so AccountFunctions object will not have it's own context
This code simply assume that AccountFunctions will be created normally through intent but in this case it is like a simple class object which has no connection with activity life-cycle calls.
so your code will look like
public Boolean validateUserToken(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
String accessToken = sharedPref.getString(context.getString(R.string.user_access_token), null);
DateTime expiryDate = new DateTime(sharedPref.getLong(context.getString(R.string.user_expires), 0));
if (accessToken == null || expiryDate.isBeforeNow()) {
return false;
} else {
return true;
}
}
or you can use string values directly
SharedPreferences sharedPref = context.getSharedPreferences("yourkey", Context.MODE_PRIVATE); // This is where the error is thrown
or
The better option is create a separate Util class for helper function rather like
class Util{
public static boolean validateUserToken(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
String accessToken = sharedPref.getString(context.getString(context.R.string.user_access_token), null);
DateTime expiryDate = new DateTime(sharedPref.getLong(context.getString(R.string.user_expires), 0));
if (accessToken == null || expiryDate.isBeforeNow()) {
return false;
} else {
return true;
}
}
}
from your activity call it like
Util.validateUserToken(this);

Replace SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.user_file_key), Context.MODE_PRIVATE);
with
SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE);

Related

getSharedPreferences Activity to Fragment

I'm trying to save data on Activity and read on the Fragment.
public void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(kekoyaz,mykey );
editor.apply();
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show();
}
Load data on fragment
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
String beimtext = sharedPreferences.getString(kekoyaz, "");
Toast.makeText(getActivity(), "bu"+beimtext, Toast.LENGTH_SHORT).show();
}
But getSharedPreferences turn red on the fragment and it's suggested to create SharedPreferences method. So I did and there is no error left.
private SharedPreferences getSharedPreferences(String sharedPrefs, int modePrivate) {
return null;
}
I get error when I run the app.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.prestige.user, PID: 32516
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference
at com.prestige.user.BlankFragment.loadData(BlankFragment.java:1918)
at com.prestige.user.BlankFragment.onCreateView(BlankFragment.java:1898)
UPDATE
I removed this line
/*private SharedPreferences getSharedPreferences(String sharedPrefs, int modePrivate) {
return null;
}*/
and I use your code
public void loadData() {
getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String beimtext = sharedPreferences.getString(kekoyaz);
Toast.makeText(getActivity(), "bu"+beimtext, Toast.LENGTH_SHORT).show();
}
I add
private ResourceBundle sharedPreferences;
But I got an error again.
After you update your question, you getSharedPreferences() with Activity but did't assign sharedPreferences variable value
Replace your code with below.
public void loadData() {
sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String beimtext = sharedPreferences.getString(kekoyaz);
Toast.makeText(getActivity(), "bu"+beimtext, Toast.LENGTH_SHORT).show();
}
This is because getSharedPreferences need a Context.
So, you can use the following:
getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);

SharedPreference doesn't contain anything inside Broadcast Receiver

So I'm new to android and I have developed a simple alarm clock app. Problem is that my alarms resets when I reboot my phone, so I created a receiver which starts at boot. This receiver is supposed to get my list of quickAlarms from my shared preference, loop through it and then send them to my AlarmService. The problem is that I am unable to get hold of the sharedPreference.
I have tried these methods:
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
sharedPref = context.getSharedPreferences("my_pref", Context.MODE_PRIVATE);
This is the broadcastReceiver called upon boot:
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BootReceiver", "BootReceiver called");
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
//sharedPref = context.getSharedPreferences("my_pref", Context.MODE_PRIVATE);
if(sharedPref.contains("alarm")){
Log.d("BootReceiver", "SharedPreference do contain alarms, trying to set them...");
alarmService= new AlarmService(context);
activate(context);
}else{
Log.d("BootReceiver", "SharedPreference does not contain any alarms.");
//I always get this message, so sharedPref never contains anything here!
}
}
/**
* Loops through the stored list of QuickAlarms, checks if the are set to on and then reshedules them.
* #param context
*/
public void activate(Context context) {
Gson gson = new Gson();
Type type = new TypeToken<List<QuickAlarm>>() {}.getType();
List<QuickAlarm> alarmList = gson.fromJson(sharedPref.getString("alarm", ""), type);
Iterator<QuickAlarm> alarmIterator = alarmList.iterator();
while(alarmIterator.hasNext()){
if(alarmIterator.next().isActive()){
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", alarmIterator.next().getTime()).setAction("CREATE").putExtra("repeat", alarmIterator.next().getRepeat()).putExtra("id" , alarmIterator.next().getID()).putExtra("desc", alarmIterator.next().getDesc()));
}
}
Log.d("BootReceiver", "All alarms are set again!");
}}
Here is the code in MainActivity were I declare the sharedpreference and use it in the Controller class:
private SharedPreferences sharedPref;
//...
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
controller = new Controller(sharedPref, this.getApplicationContext());
Then it's really the Controller which use it:
public Controller(SharedPreferences sharedPref, Context context) {
this.context = context;
this.sharedPref = sharedPref;
editor = sharedPref.edit();
}
//...
public void addQuickAlarm(QuickAlarm qa, int id) {
Gson gson = new Gson();
Type type = new TypeToken<List<QuickAlarm>>() {
}.getType();
List<QuickAlarm> alarms;
if (gson.fromJson(sharedPref.getString("alarm", ""), type) == null) {
alarms = new ArrayList<>();
} else {
alarms = gson.fromJson(sharedPref.getString("alarm", ""), type);
}
if (id == -10) {
alarms.add(qa);
Log.d("Controller", "QuickAlarm added to pref");
} else {
alarms.remove(id);
alarms.add(id, qa);
Log.d("Controller", "QuickAlarm edited to pref");
}
String jsonAlarm = gson.toJson(alarms); //converting list to json and saving back
editor.putString("alarm", jsonAlarm);
editor.commit();
}
public void activateAlarm(boolean on, int id) {
Gson gson = new Gson();
Type type = new TypeToken<List<QuickAlarm>>() {
}.getType();
List<QuickAlarm> alarmList = gson.fromJson(sharedPref.getString("alarm", ""), type);
QuickAlarm qa = alarmList.get(id);
qa.setActive(on);
int[] repeat = qa.getRepeat();
addQuickAlarm(qa, id);
if (on) {
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", qa.getTime()).setAction("CREATE").putExtra("repeat", repeat).putExtra("id" , id).putExtra("desc", qa.getDesc()));
} else {
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", qa.getTime()).setAction("CANCEL").putExtra("id" , id));
}
}
you need to add the "alarm" key and its value to your sharedpreference when you are setting the alarm alert something like this
sharedPref = context.getSharedPreferences("my_pref", Context.MODE_PRIVATE);
or
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor=sharedPref.edit();
editor.putString("alarm", "value u want to keep");
editor.commit();
Unable to start receiver com.example.user.alarmclock.Local.StartMyServiceAtBootReceiver: java.util.NoSuchElementException because after alarmIterator.next().isActive() this you are calling another next() like this alarmIterator.next().getTime() which mean you are asking for List<QuickAlarm > next item object(QuickAlarm ) which is not there so only you are getting the error. change your code to this because even you mean if in this object(QuickAlarm ) isActive() is true then pull other info from this object(QuickAlarm ) like getTime(),getRepeat() etc.
while(alarmIterator.hasNext()){
QuickAlarm qm=alarmIterator.next()
if(qm.isActive()){
alarmService.onHandleIntent(new Intent(context, AlarmReceiver.class).putExtra("time", qm.getTime()).setAction("CREATE").putExtra("repeat", qm.getRepeat()).putExtra("id" , qm.getID()).putExtra("desc", qm.getDesc()));
}
}

SharedPreferences/Context Throw NullPointerException

I'm trying to pass some values from an activity to a non-activity receiver class in order to create a notification. I can't see why I'm getting an error on this one. I mean, I passed the context, retrieved it, and used it accordingly. I read some threads about this issue and did my best to solve it, but this is how far I could come. I'm getting an eror on this line:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
DailyForecastActivity.java
public class DailyForecastActivity extends AppCompatActivity {
private Daily[] mDays;
public static Context contextOfApplication;
#Bind(android.R.id.list)
ListView mListView;
#Bind(android.R.id.empty)
TextView mEmptyTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_forecast);
ButterKnife.bind(this);
contextOfApplication = getApplicationContext();
GPSTracker gpsTracker = new GPSTracker(this);
TextView mLocationLabel = (TextView) findViewById(R.id.locationLabel);
Intent intent = getIntent();
Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.DAILY_FORECAST);
mDays = Arrays.copyOf(parcelables, parcelables.length, Daily[].class);
DayAdapter adapter = new DayAdapter(this, mDays);
mListView.setAdapter(adapter);
mListView.setEmptyView(mEmptyTextView);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String dayOfTheWeek = mDays[position].getDayOfTheWeek();
String condition = mDays[position].getSummary();
String tempMin = mDays[position].getTempMin() + "";
String tempMax = mDays[position].getTempMax() + "";
int icon = mDays[position].getIconId();
String message = String.format("%s Summary: %s", dayOfTheWeek, condition);
Toast.makeText(DailyForecastActivity.this, message, Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("summary", condition);
editor.putString("tempMin", tempMin);
editor.putString("tempMax", tempMax);
editor.putString("dayOfTheWeek", dayOfTheWeek);
editor.putInt("icon", icon);
editor.apply();
}
});
String area = gpsTracker.getSubLocality(this);
String city = gpsTracker.getAdminArea(this);
String country = gpsTracker.getCountryName(this);
mLocationLabel.setText(area + ", " + city + ", " + country);
}
public static Context getContextOfApplication(){
return contextOfApplication;
}
}
Receiver.java
public class Receiver extends BroadcastReceiver{
Context applicationContext = DailyForecastActivity.getContextOfApplication();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
String summary = preferences.getString("summary", null);
String tempMin = preferences.getString("tempMin", null);
String tempMax = preferences.getString("tempMax", null);
String dayOfTheWeek = preferences.getString("dayOfTheWeek", null);
int icon = preferences.getInt("icon", 0);
#Override
public void onReceive(Context context, Intent intent) {
this.applicationContext = context;
PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(icon)
.setContentTitle(dayOfTheWeek + " Weather")
.setContentText(summary + "Temperature: " + tempMax + "/" + tempMin)
.setTicker("Daily Weather");
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
logcat
java.lang.RuntimeException: Unable to instantiate receiver com.theoc.stormy.Receiver: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2565)
at android.app.ActivityThread.access$1700(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
at com.theoc.stormy.Receiver.<init>(Receiver.java:42)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2560)
at android.app.ActivityThread.access$1700(ActivityThread.java:148) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5272) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704) 
EDIT
I solved the NPE error, but now I'm getting "null" for my SharedPreferences values. I ran a debug in DailyForecastActivity, where I'm putting the values, and there seems to be no problem there. I'm able to put all the values I want. Looks like I'm unable to retrieve the SharedPreferences in Receive.java. Also as a side note, I'm getting the notification sound for some reason, but not getting any notification at all.
initialize SharedPreference in onReceive
preferences = PreferenceManager.getDefaultSharedPreferences(context);
It might be possible when your BroadcastReceiver is called your activity is null
Try to do this:
First, instatiate your application in the manifest by linking to a class
<application
android:name = ".App"
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name" >
Then implement the following method whitin your application class
public class App extends Application {
private static final String TAG = ".App";
private static Context context = null;
public void onCreate(){
super.onCreate();
context = getApplicationContext();
}
#SuppressWarnings("unused")
public static Context getContext() {
if (context != null) {
return context;
} else {
Log.e(TAG, "App was not successfully created");
throw new Error("App was not successfully created");
}
}
}
I always get my shared preferences by using:
context.getSharedPreferences(PREFERENCE_FILENAME, Context.MODE_PRIVATE);
You can also verify whether the preference file is created or not in your application data/ directory.
Please, read carefully how shared preferences works in android.
By calling in DailyForecastActivity.java
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
and in Receiver.java
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
You are calling for two different instances of SharedPreferences. You are saving in one, then you are trying to get from second, where you didn't save anything, so you are getting null for all values. You must unite it and use the same in first and second situation, like:
SharedPreferences sharedPref = getPreferences("MyPref", Context.MODE_PRIVATE);
in DailyForecastActivity and
SharedPreferences sharedPref = context.getPreferences("MyPref", Context.MODE_PRIVATE);
in Receiver, which will result in getting the same instance.
Also you can try using the same Context. Context get from getActivity() is not the same Context get from getApplicationContext(). So use getApplicationContext() in both situations or pass Context via parameter in constructor from activity.

shared preference Boolean is always returning false

I am using shared preference. Why this method is always returning false ?(this code btw from this tutorial) when or how it should return true? I want to check if its true to enter another activity
public boolean isLoggedIn(){
return pref.getBoolean("login", false);
}
when I am creating a user , I am adding Boolean true
public void createLoginSession(String name, String email){
// Storing login value as TRUE
Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
System.out.println("login1");
editor.putBoolean("login", true);
// Storing name in pref
editor.putString("name", name);
// Storing email in pref
editor.putString("email", email);
// commit changes
editor.commit();
}
this method is to check the return islogin true or false in this case its always false, how to fix that to return it ?
/**
* 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()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Register.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);
}
else {
Intent i = new Intent(_context, UserProfile.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);
}
}
Session manager class
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_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// 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 email){
// Storing login value as TRUE
Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
System.out.println("login1");
editor.putBoolean("login", true);
// Storing name in pref
editor.putString("name", name);
// Storing email in pref
editor.putString("email", email);
// commit changes
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(){
// Check login status
// editor.putBoolean("login", true);
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Register.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);
}
else {
Intent i = new Intent(_context, UserProfile.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 HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* 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_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean("login", false);
}
}
edit
when I removed the editor from the cursor and I add it here, it worked
public void checkLogin(){
// Check login status
pref = PreferenceManager.getDefaultSharedPreferences(_context);
editor = pref.edit();
editor.putBoolean("login", true);
if(!this.isLoggedIn()){
Toast.makeText(_context, " Login", Toast.LENGTH_SHORT).show();
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Register.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
but the weird when If I am addin here , its not working
public void createLoginSession(String name, String email){
// Storing login value as TRUE
Toast.makeText(_context, "Create", Toast.LENGTH_SHORT).show();
System.out.println("login1");
pref = PreferenceManager.getDefaultSharedPreferences(_context);
// pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
editor.putBoolean("login", true);
...
Instead of
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
try
pref = PreferenceManager.getDefaultSharedPreferences(context);
Here is my context (ctx) in the debugger.
So the following is how you can check the preference file to verify that it matches. I also wrote the code different in the third screen shot to demonstrate how a small difference can change the preference location.
In the first screen shot, notice the debugger showing the location of the preference file I am writing to.
Next, look at the location of the file I am reading from and how I initialized my pref variable. My saved preference is true, just as I saved it in the last screen.
Finally, I initialized my pref differently. See the difference? My boolean is now false(default) and the file location is different.
Now, maybe you are setting up your preferences the same every time. Check to be sure. I had this exact problem years ago and it drove me nuts till I realized I had different preference files being used. This is how I found the problem.
Finally, look at the different ways I tried to get my context. See how each one is different in the debugger? This is probably not your issue, but when you have weird disconnects going on, look twice at exactly how you hook everything up.
I hope this helps...
Make sure that the editor is connected to the SharedPreferences. I don't see something unusual but it would be safer to use prefs.edit()...commit();
You did not mention how you are retrieving the value. But while committing the value, are you writing to the same preference file that you are retrieving from ?
SharedPreferences myPref = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = myPrefFIle.edit();
editor.putBoolean("login", true);
editor.commit();
Otherwise, it is quite simple as you know.
EDIT
You can try this preference helper file. Replace your with this and try. If you still see the issue, then it is something else but not in preferences.
public class SharedPreferencesHelper {
public static final String PFO_SHARED_PREF_NAME = "prefs_file";
public static final String PREF_PLUG_STATE = "plug_state";
public static final String PREF_ICE_BUTTON_STATE = "ice_button_state";
private final SharedPreferences mPreferences;
private final Context mContext;
private static SharedPreferencesHelper instance = null;
private SharedPreferencesHelper(Context context) {
mContext = context;
mPreferences = context.getSharedPreferences(PFO_SHARED_PREF_NAME,
Context.MODE_PRIVATE);
}
public static SharedPreferencesHelper getInstance(final Context context) {
if (instance == null) {
instance = new SharedPreferencesHelper(context.getApplicationContext());
}
return instance;
}
public boolean getPlugState() {
return mPreferences.getBoolean(PREF_PLUG_STATE, false);
}
public void storePlugState(boolean state) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean(PREF_PLUG_STATE, state);
editor.apply();
}
}
You call like this, for ex:
boolean pullPlugState = mPref.getPlugState();
This is a singleton but you can change it once it starts working. Or else this is not a big object so it's perfectly fine with singleton.

SharedPreferences not being cleared android

I have an app where a user logs in and his details are saved so that the next time he starts the app he doesn't need to log in again.I have used SharedPreferences for this purpose. Now when I implement a logout function, I clear the preferences and I get a Map with 0 elements. Also I delete the Preference file. But when another user logs in he can still see the previous users details instead of his. How can I solve this?
Here is my code:-
SessionManagement.java
public class SessionManagement extends Application
{
static SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// ContextS
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyUserDetails";
// 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_EMAILID = "email";
// Email address (make variable public to access from outside)
public static final String KEY_USERSNAME = "usersname";
public static final String KEY_DEVICEREGISTERED = "deviceregistered";
// Constructor
public SessionManagement(Context context)
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(String emailId, String usersname)
{
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
editor.putBoolean(KEY_DEVICEREGISTERED, true);
editor.putString(KEY_EMAILID, emailId);
editor.putString(KEY_USERSNAME, usersname);
editor.commit();
// commit changes
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails()
{
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_EMAILID, pref.getString(KEY_EMAILID, null));
user.put(KEY_USERSNAME, pref.getString(KEY_USERSNAME, null));
// return user
return user;
}
/**
* 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(this, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
// This function clears all session data and redirect the user to LoginActivity
/**
* Clear session details
* */
public void logoutUser()
{
// Clearing all data from Shared Preferences
editor.remove(KEY_EMAILID);
editor.remove(KEY_USERSNAME);
editor.remove(IS_LOGIN);
editor.clear();
editor.commit();
}
public boolean isLoggedIn()
{
return pref.getBoolean(IS_LOGIN, false);
}
}
Login.java
sessionManager = new SessionManagement(getApplicationContext());
if(sessionManager.isLoggedIn())
{
//Go directly to main activity
HashMap<String, String> userDetails = sessionManager.getUserDetails();
startMyActivity();
finish();
}
else
{
sessionManager.createLoginSession(email, username);
}
public void startMyActivity()
{
// TODO Auto-generated method stub
Intent in = new Intent(getApplicationContext(), Details1.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
}
Logout.java
SessionManagement session = new SessionManagement(getApplicationContext());
session.logoutUser();
ClearData cl = new ClearData();
cl.clearApplicationData(getApplicationContext());
Intent i = new Intent(Home.this, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(i);
ClearData.java
public class ClearData
{
public static void clearApplicationData(Context context)
{
File cache = context.getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
File f = new File(appDir, s);
if(deleteDir(f))
Log.i("TAG", String.format("**************** DELETED -> (%s) *******************",
f.getAbsolutePath()));
}
}
}
private static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
Instead of removing value from sharedpreference you can just edit value of sharedpreference with null value.
public void logoutUser()
{
editor.putBoolean(IS_LOGIN, false);
editor.putBoolean(KEY_DEVICEREGISTERED, false);
editor.putString(KEY_EMAILID, null);
editor.putString(KEY_USERSNAME, null);
editor.commit();
}
i think this will work..
You can change the values of Shared preferences.
public void logoutUser()
{
editor.putBoolean(IS_LOGIN, false);
editor.putBoolean(KEY_DEVICEREGISTERED, false);
editor.putString(KEY_EMAILID, "");
editor.putString(KEY_USERSNAME, "");
editor.clear();
editor.commit();
}
or You try this code. Clear your Shared preferences values.
pref.edit().clear().commit();
if your are using Marshmallow then
Add file in xml folder
mybackupscheme.xml
<full-backup-content>
<exclude domain="sharedpref" path="yourshared pref name.xml"/>
</full-backup-content>
then add in AndroidManifest.xml
<application
...
android:fullBackupOnly="false"
android:fullBackupContent="#xml/mybackupscheme"
/>
Hope this using this your issue will be resolved.
Try to get editor every time before calling commit().
If this not works, check contexts, that are returning preferences, they must be in one application and process.
I think problem is in your way of working with editor.
I think there is problem in your view of your editor and preference globalization you have to create preference and editor locally....
Because you are getting preferences
public SessionManagement(Context context)
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
And now you are not getting any updated Preferences....
Each and every time when you have to work with your preferences...
Initialize preference and editor every time.
Either logging In or log out.

Categories

Resources