Error loading SharedPreferences on startup - android

I'm obviously doing something wrong. On my splash screen, when it decides which activity to go to, I have the following code:
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
boolean disclamerChecked = getPrefs.getBoolean("disclamer", false);
boolean medicalScreeningChecked = getPrefs.getBoolean("screening", false);
So, I'm trying to read 2 Boolean that should be false on app installation and
when the setup is done it should be permanently true.
Now, in my Activities (Disclamer only at the moment) I have the following thing:
private void setDisclamerPropertie() {
// TODO Auto-generated method stub
startupPrefs= getSharedPreferences("startupPrefs", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = startupPrefs.edit();
editor.putBoolean("disclamer", true);
editor.commit();
return;
}
This function is called in On Create function, and when "accept" button is clicked it should save the Shared Preference (Or at least that is what I need to happen).
Button works, it goes to next activity and that one goes to next again, but when I reload the App, it seems that Boolean are not saved and app asks again for the confirmations.
So, where am I wrong, in writing preferences, or something is missing in reading correct preferences?

You are reading from the default shared preferences, but writing to a named one ("startupPrefs"), so there are 2 separate instances of shared preferences

You're using different preferences.
startupPrefs= getSharedPreferences("startupPrefs", MODE_WORLD_WRITEABLE);
This should also be:
startupPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

Related

How to create pop-up when first open app in Android?

I write an application, I want to get a phone number, but getline1number() not working on any devices.
So, I want to create a pop-up to enter a phone number and submit to save and don't show in next time open app.
Like this:
You can always use SharedPreferences to do such things:
SharedPreferences sp = getSharedPreferences("FirstTimeFile", Context.MODE_PRIVATE);
/**
* when the app is opened for the first time, no such variable
* (appIsOpenedForTheFirstTime) exists. So, it becomes true.
*/
boolean appIsOpenedForTheFirstTime = sp.getBoolean("IsAppOpenedForFirstTime",true);
//since it is true, it will be set to false after the execution of following block:
if(appIsOpenedForTheFirstTime) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("IsAppOpenedForFirstTime", false);
editor.commit();
//PUT THE CODE FOR YOUR POPUP HERE
}
As the SharedPreferences values remain in the application data even after you close the app, so the next time you open the app, the value of appIsOpenedForTheFirstTime will be false and hence your pop-up code won't be executed.
Ah, as a side-note, if you clear the app data, everything gets cleared - including the SharedPreferences. Read this official article for in-depth understanding.

To create a walkthrough page that appears only when the application is installed

I'm developing an mobile where the walkthrough page about the application should appear only once the application is installed. Can anyone help me resolving this issue with a clear example.
Add the following code in your method:
SharedPreferences prefs = getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE);
// Default value returned by next line is true.
boolean firstLaunch = prefs.getBoolean("firstLaunch", true);
if (firstLaunch) {
// Do whatever you want here. This will be called only the first time the app launches.
// Then edit the SharedPreferences and put the value as false. Unless changed back to true, this if statement/loop will never be called again.
prefs.edit().putBoolean("firstLaunch", false).apply();
}
Note: PREFERENCES_NAME is just a String. It can be anything. I suggest you use the same PREFERENCES_NAME in all of your app, in case you need to access SharedPreferences somewhere else.

I want to know how to check whether a checkbox is checked or not in android from broadcast receiver

I want to know how to check whether a checkbox is checked or not when an application is not running. Please help me. I'm making a call blocker, and I'm stuck.
When the application is not running, how can it check whether the checkbox is checked or not.
Android provides SharedPreferences class which is an utility that helps you to save user settings within your app internal memory and can be accessed by providing your application context.
Let's say that the user has checked the checkbox control, you could save that choice using SharedPreferences instance saving it onto disk.
For example:
myCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
SharedPreferences prefs = yourActivityContext.getSharedPrefences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor = prefs.edit(); //Create this instance in order to save data
editor.putBoolean("checked", isChecked); //Store the checkbox value
editor.commit(); //Call this to save the preferences to disk
}
}
);
Then in your BroadcastReceiver:
#Override
public void onReceive(Context context, Intent data) {
SharedPreferences prefs = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
boolean checkboxValue = prefs.getBoolean("checked", false);
//The second argument provide a default value if you haven't saved that setting before.
}
you can store checkbox value in database or web api and check through Android Services class.
Every time you start an application, a completely new instance of the program is created. And once the application terminates, the instance that was running no longer exists for you to check its state.
What you will have to do is...
Store the settings in a file or database when the program closes (or when the user hits "save" depending on how you design it)
When the application opens, have it read the settings and populate the screen (e.g., checkboxes) with its contents
If you didn't write the program that owns the checkbox (which wasn't clear in your original post), then the program must already do this; otherwise, it would have no way to re-populate the screen when it starts up. In this case, all you have to do is find out what the file or database table stores the info you need and figure out how to extract the data you need from that location.
Use SharedPreferences. In the onCheckChangedListener, just store a shared preferences with the boolean value associated with the checkbox. The broadcast receiver should have the same context, so you should be able to access the shared preference from there.

How to keep the project always be open using login page on android/eclipse

I have one log in page for the project 'x'.My need is if at first i entered into the project by providing proper values in to the log in page of the project.The project always want to be signed-in, whenever i try to open the project.How to achieve this concept?
Thanks for your precious time!..
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of the getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
For more info, check this link:
Making data persistent in android
Whenever you login set the user inside the preference file. Then in your main activity give a check whether you have value for this preference or not. If present, goto the landing page. Otherwise show the login page.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getLandingPage();
}
private void getLandingPage() {
if (isLoggedIn()) {
//goto login page
} else {
//goto landing page
}
}
/**
* Checks whether preference contains any value
*
* #return
*/
private boolean isLoggedIn() {
return ProjectPreferences.getUserName() == ProjectPreferences.NULL_STRING
? true
: false;
}
}
Also don't forget to set username while you login.

SharedPreferences value is not updated

I am trying to update the values of SharedPreferences, here is my code:
edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putString(Settings.PREF_USERNAME+"",txtuser);
edit.putString(Settings.PREF_PASSWORD+"",txtpass);
edit.commit();"
The problem is that when I am accessing this values, it is not returning updated values, it gives me a value of SharedPreferences.
But when I am confirming the data in XML file ,the data updated in that.
And after restarting my application I am getting that updated values. So it requires me to restart the application to get updated values.
So, how to get those updated values once it changes?
Thanks in advance
Here is my whole code:
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
ctx=this;
status=PreferenceManager.getDefaultSharedPreferences(this).getString(Settings.PREF_STATUS, Settings.DEFAULT_STATUS);// get old value
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
on(ctx,true);// function will call and value is updated
}
}});
status=PreferenceManager.getDefaultSharedPreferences(this).getString(Settings.PREF_STATUS, Settings.DEFAULT_STATUS);// this should give me a updated value but gives old value
}
public static boolean on(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Settings.PREF_ON, Settings.DEFAULT_ON);
}
public static void on(Context context,boolean on) {
if (on) Receiver.engine(context).isRegistered(); //
}
**********in reciver file***********
public void isRegistered ) {
Editor edit = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).edit();
edit.putString(Settings.PREF_STATUS+"","0");
edit.commit();
}
Instead of using edit.commit();, you should use edit.apply();. Apply will update the preference object instantly and will save the new values asynchronously, so allowing you to read the latest values.
commit()
Commit your preferences changes back from this Editor to the
SharedPreferences object it is editing. This atomically performs the
requested modifications, replacing whatever is currently in the
SharedPreferences.
Note that when two editors are modifying preferences at the same time,
the last one to call commit wins.
If you don't care about the return value and you're using this from
your application's main thread, consider using apply() instead.
apply()
Unlike commit(), which writes its preferences out to persistent
storage synchronously, apply() commits its changes to the in-memory
SharedPreferences immediately but starts an asynchronous commit to
disk and you won't be notified of any failures. If another editor on
this SharedPreferences does a regular commit() while a apply() is
still outstanding, the commit() will block until all async commits are
completed as well as the commit itself.
As SharedPreferences instances are singletons within a process, it's
safe to replace any instance of commit() with apply() if you were
already ignoring the return value.
You don't need to worry about Android component lifecycles and their
interaction with apply() writing to disk. The framework makes sure
in-flight disk writes from apply() complete before switching states.
Well, even if my answer came 3 years after the question, I hope it will help. The problem don't seem to came from commit or apply but from the code structure.
Let's explain: on a smartphone, you run an APP but you don't quit the APP as we do on computers.
This mean when you come back to the menu of the smartphone, the APP is still "running". When you "click" again on the APP icon, you don't re-run the APP but just awake it.
In juned code, we can see he calls getDefaultSharedPreferences inside his Create function.
So he calls getDefaultSharedPreferences when he runs first time the APP. But when he sets the APP on background and then awakes the APP, the call is not done.
I've had the same problem:
I check if I have SharedPreference for my APP. If not, I prompt a form to ask value to the user.
If yes, I check the date of the preferences. If too old, I prompt the form.
After the form, I save the preferences with the current date.
What I noticed is that the test about the existence of the SharedPreference (which was set at the same location than the one of juned) was done only at first run of the APP but not when I awake the APP. This mean that I was unable to check the time limite of my SharedPreferences!
How to solve that?
Just add:
#Override
public void onResume(){
super.onResume();
// And put the SharedPreferences test here
}
This code will be called at first run of the APP but also each time the user awake it.
hope it will help you..
SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefsEditr = mypref.edit();
prefsEditr.putString("Userid", UserId);
prefsEditr.commit();
String task1 = mypref.getString("Userid", "");
Try this code:
SharedPreferences edit = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor1 = edit.edit();
editor.putString(Settings.PREF_USERNAME + "", txtuser);
editor.putString(Settings.PREF_PASSWORD + "", entered_name);
editor.commit();
Try like this,
public SharedPreferences prefs;
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Settings.PREF_USERNAME+"", txtuser);
editor.putString(Settings.PREF_PASSWORD+"", entered_name);
editor.apply()
Try like this,
public SharedPreferences prefs;
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Settings.PREF_USERNAME+"", txtuser);
editor.putString(Settings.PREF_PASSWORD+"", entered_name);
editor.commit();

Categories

Resources