I'm trying to use SharedPreferences in my app but it just doesn't seem to be working.
First, I declare SharedPreferences as a global variable in the activity where I'm planning to use them:
SharedPreferences prefs;
Then I set the default SharedPreferences in onCreate:
prefs = getSharedPreferences("urnikSp", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("schudeleDownloaded", false);
editor.commit();
I then change the boolean value when a certain action is completed:
prefs.edit().putBoolean("schudeleDownloaded", true).commit();
And then in the same activity (when it is restarted), I check for the boolean value in onCreate like this:
boolean schudeleDownloaded = prefs.getBoolean("schudeleDownloaded", false);
if (!schudeleDownloaded){
new PopulateDatabase().execute();
}
And even though I clearly set the new value to "true" upon completing a certain action, the IF statement you see above still executes because the boolean value still seems to be false.
What am I doing wrong?
If you are recreating your activity, the onCreate() method will be called again, so I think you change his value back to false
Let me do a wild guess. Because when you restart, you set it to false again.... It is in onCreate function.
You have to create a separate SharedPreferences.Editor instance. So instead of doing this:
prefs.edit().putBoolean("schudeleDownloaded", true).commit();
Try this:
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("schedeleDownloaded", true);
editor.commit();
Related
I'm trying to create a simple Settings Activity with a single setting to change the language of the App.
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/locale">
<ListPreference
android:key="lang"
android:title="#string/language"
android:summary="#string/languageDesc"
android:entries="#array/languages"
android:entryValues="#array/languageValues"
android:defaultValue="#string/locale_en"/>
</PreferenceCategory>
public class TCPreferenceActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("lang")) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("lang", sharedPreferences.getString(key, "en_US"));
editor.commit();
settings();
}
}
public void settings() {
Intent intent = new Intent(this, TCPreferenceActivity.class);
intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, TCPreferenceFragment.class.getName());
intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true);
startActivity(intent);
}
#Override
protected void attachBaseContext(Context newBase) {
SharedPreferences pref = newBase.getSharedPreferences("lang", MODE_PRIVATE);
String lang = pref.getString("lang", null);
Locale locale = new Locale(lang);
Context context = TCContextWrapper.wrap(newBase, locale);
super.attachBaseContext(newBase);
}
}
When I debug the activity, i see the updated value being received in the method onSharedPreferenceChanged.
However when i call the Intent to reload the activity, with the context wrapper in order to change the language, the value received from the call to newBase.getSharedPreferences("lang", MODE_PRIVATE) is still the original unchanged value.
When i click again on the preference in the interface, i see that the value hash changed.
Do I need to save the value?
Why doesn't it changed in the SharedPreferences class?
I'm trying to replicate what0s being done in the exemple here:
Android context.getResources.updateConfiguration() deprecated
Thanks in advance.
Try changing:
SharedPreferences pref = newBase.getSharedPreferences("lang", MODE_PRIVATE);
To:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(TCPreferenceActivity.this);
For what ever reason, you are loading up private "lang" preferences, which im pretty sure you are not saving to. Use the default preferences instead which the activity should be by default using else where.
I would rather that you user apply() instead of commit().
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.
Do this;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("lang", sharedPreferences.getString(key, "en_US"));
editor.apply();
I have two buttons(button1, button2) in my activty. botton1 is 'Enabled'(true) , while the other one isn't.
When I click on button1, button2 becomes 'Enabled'. I want to record this activity in this state for the next utilization of my application.
You can save state in sharedPrefrences, try this
SharedPreferences prefs = getSharedPreferences("Your preference name here", MODE_PRIVATE)
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
b2.setEnabled(true);
prefs.edit().putBoolean("b2enabled", true).commit();//saving State here
}
});
And now where you want to use this state simple get the state as.
Boolean b2state= prefs.getBoolean("b2enabled", false); //false is the default value
And if you want to enable or disable button on result do
if (b2state){
b2.enabled(true);
}
else{
b2.enabled(false);
}
Well, you can use the help of a data storage option. For a simple task like this,
shared preference is enough.
use something like this to store the state change.
function setState(boolean state){
SharedPreferences sharedPref =this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("state",state);
}
you can retrieve the data at anytime (usually in in the beginning) like this. Note that the second argument serves the default value.
int state=this.getPreferences(Context.MODE_PRIVATE).getBoolean("state",false);
Hope this helps.
I have an app, and I am trying to limit the number of button clicks to five, and then once the user has pressed this button five times it should disable.
However I am getting the above error and I am not sure why.
Any ideas ?
buttonadd.setOnClickListener(new OnClickListener () {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
int clicks = 0;
clicks++;
if (clicks >= 5){
buttonadd.setEnabled(false);
}
SharedPreferences prefs = Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("clicks", clicks);
editor.apply();
}
});
You are wrongly trying to use the virtual method getSharedPreferences() in a static way, that's why its giving that compile-time error.
If that code is in an Activity, replace
Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
with
getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
If it is in a Fragment, use
getActivity().getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
EDIT:
use
if (clicks >= 5){
buttonadd.setEnabled(false);
buttonadd.setClickable(false);
buttonadd.setFocusable(false);
buttonadd.setFocusableInTouchMode(false);
}
and make clicks a class member, i.e. declare it as
private int clicks;
in the Activity.
EDIT 2:
I think I have understood the mistake you are making. In your code, replace
int clicks = 0;
with
SharedPreferences prefs = getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int clicks = prefs.getInt("clicks", 0);
Try this. This should do it.
It means that you need an instance of a Context object to call the getSharedPreferences() method. If you're inside an Activity, try this:
this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE)
As the error message says getSharedPreferences() is a non-static method. When you do Context.getSharedPreferences(...) you are trying to call it directly from the class. Instead, you need to call it from a Context instance.
If your code is inside an Activity (as Activity extends Context) you can simply do:
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
I want my main activity to show a popup the on launch, this activity is the first activity that is created, but multiple instances of this activity could be created and I only want the first since launch to display this popup, so I would like to know if there how I can check this.
The most simplest way of doing it is use a static variable
How do you use it:
Define a static boolean flag and assign it false value, once the activity is created for the first time, make the flag true, and now you do your task with simple if/else condition
public static boolean flag=false;
then in onCreate
if(flag==true)
{
//Activity is not calling for first time now
}
if(flag==false)
{
//first time calling activity
flag=true;
}
Store flag in SharedPreferences which indicate is application is launched first time or not. Use Activity Oncreate method as:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and check SharedPreferences if fist time launch
SharedPreferences settings = getSharedPreferences("showpopup", 0);
SharedPreferences.Editor editor = settings.edit();
if(settings.contains("firsttime")){
// means activity not launched first time
}else{
// means activity launched first time
//store value in SharedPreferences as true
editor.putBoolean("firsttime", true);
editor.commit();
//show popup
}
}
I would use selvins approach. Unless you have a backend to your application setup and user registration, there will be no way for you to get this type of information for a specific application instance unless you use SharedPreferences
int activityLaunchCount = 0;
SharedPreferences preferences = getBaseContext().getSharedPreferences("MyPreferences", SharedPreferences.MODE_PRIVATE);
activityLaunchCount = preferences.getInt("ActivityLaunchCount", 0);
if(activityLaunchCount < 1)
{
// ** This is where you would launch you popup **
// ......
// Then you will want to do this:
// Get the SharedPreferences.Editor Object used to make changes to shared preferences
SharedPreferences.Editor editor = preferences.edit();
// Then I would Increment this counter by 1, so if will never popup again.
activityLaunchCount += 1;
// Store the New Value
editor.putInt("ActivityLaunchCount", activityLaunchCount);
// You Must call this to make the changes
editor.commit();
}else{
// If you application is run one time, this will continue to execute each subsequent time.
// TODO: Normal Behavior without showing a popup of some sort before proceeding.
}
Then when you want to Close the application
Override the Activity finish() method
#Override public void finish()
{
super.finish();
// Get the SharedPreferences.Editor Object used to make changes to shared preferences
SharedPreferences.Editor editor = preferences.edit();
// Store the New Value
editor.putInt("ActivityLaunchCount", 0);
// You Must call this to make the changes
editor.commit();
}
im building a app, found a java part that lets me show an activity only at first start.
this works but when i kill the app or reboot my phone it goes back, can anyone help me out with this?
im using this in my main activity (Toolz.java)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Prefs.firststart == false) {
setContentView(R.layout.toolz);
} else {
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
and i added this to First.java
Prefs.firststart=false;
and i made the Prefs.java and added this
public class Prefs {
public static boolean firststart = true;
}
you will need to use SharedPreferences instead o static variable for saving data which also available when app killed or device reboot.
you can see following tutorial how we use SharedPreferences for saving and reading data from SharedPreferences
Shared Preferences
When the app restarts all your code will start from the starting point (i.e Prefs.firststart will be set to true). Instead, you need to make a persistent variable that is saved throughout sessions. If you're using a DB you could use that, or you could use the built-in SharedPreferences, as such:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = this.getPreferences(MODE_PRIVATE);
if (prefs.contains("started")) {
setContentView(R.layout.toolz);
} else {
//Add the preference:
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("started",true);
editor.apply();
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
When you kill your app, the values are going to reset to their initial values. Your boolean will be equal to true. I suggest saving the state of the variable using SharedPreferences. Check out this other question someone asked about saving.
How to save a state of a variable in android app and use it
Try it like this
//**** First start *****
//you get the prefs for your app using a pref name
String PREFS_NAME = "myAppPrefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//persist the boolean value in preferences using a key-value approach
editor.putBoolean("pref_app_started", true);
//commit the changes
editor.commit();
and when you start the app you check for that pref
//**** next start *****
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//now we get the saved boolean using the key we previously uesd when setting it
//the second parameter is the default value for the flag in case it was never set
boolean wasAppStarted = settings.getBoolean("pref_app_started", false);
//now you can use your wasAppStarted flag to decide what you do further