How to solve the bug in CheckBoxPreference Default Value in android? - java

Because my mainActivity does not run my Tab2Activity at startup until the user press the setting button to run the PreferenceActivity, therefore i have to first check the audioStatus boolean value in order to avoid unwanted boolean result but after this step i'm kinna lost because of the bug in CheckBoxPreference it gives me...
Now i don't know how to work with the logic comparison to get the audio even without navigating to Tab2Activity? Main problem here i'm facing is working with the logics yet getting the desirable result..
I'm kinna new in java/android and currently creating an car blackbox app can someone help me... Thanks :)
My mainActivity file
if(Tab2Activity.audioPref == false)
audioStatus = false;
else
audioStatus = Tab2Activity.audioPref;
if(audioStatus == false)
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
if(audioStatus == false)
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
My Tab2Activity.java file
public static boolean audioPref;
public static String timeIntervalPref;
public void getPrefs() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
audioPref = prefs.getBoolean("AudioPref", true);//Suppose to produce "false" isn't it?
timeIntervalPref = prefs.getString("TimeIntervalPref", "60000");
}
}
My xml file
<CheckBoxPreference
android:title="Audio"
android:defaultValue="True"
android:summary="Select w/o Audio when Recording"
android:key="AudioPref" />

save your settings to a SharedPreferences then read them from there rather than relying on the state of a public boolean in the Tab2Activity.
http://developer.android.com/reference/android/content/SharedPreferences.html
example of use:
http://saigeethamn.blogspot.com/2009/10/shared-preferences-android-developer.html
EDIT: I don't know why you are trying to get the preferences from tab2activity.
why wouldn't you do the following in mainActivity:
SharedPreferences prefs=PreferenceManager.getDefaultSharedreferences(getBaseContext());
audioStatus=prefs.getBoolean("AudioPref",true); // (only use true if you want the default to be true if the value has not yet been set, otherwise you should be doing ("AudioPref",false) )
if(!audioStatus)
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
}
The bug you linked describes issues when you try to set default shared preference values to 'false'. If you want that to be the default, then just use "false" as the default value when you go to retrieve the value using getBoolean(string,defValue)

Related

SharedPreferences does not return the default value

I have a sharedpreferences and I have created a method for it to be checked if it is the user's first time in the app. But it always returns the opposite of the default value.
My code:
public static Boolean getFirstOnApp(Context context) {
SharedPreferences pref = context.getSharedPreferences(LOGIN_PREFS_NAME, Context.MODE_PRIVATE);
return pref.getBoolean(KEY_FIRST_TIME_ON_APP, true);
}
Is always returns false.
I call it on my controller:
if (SaveSharedPreferences.getFirstOnApp(context)) {
fabAtivaMapeamento.performClick();
SaveSharedPreferences.setFirstOnApp(context, false);
}
SaveSharedPreferences.setFirstOnApp(context, false); has never been called before. It is only changed within this If
I already uninstalled the app, forced it to stop, cleared data and cache.
How to solve?
use like this to check if it's first time or not
SharedPreferences pref = getSharedPreferences(LOGIN_PREFS_NAME, Context.MODE_PRIVATE);
if (pref.getBoolean(KEY_FIRST_TIME_ON_APP, false)) {
//in here it's not for first time
} else {
//in here it's first time
}
Edit - Check if the following works.
public static Boolean getFirstOnApp(Context context) {
SharedPreferences pref = context.getSharedPreferences(LOGIN_PREFS_NAME, Context.MODE_PRIVATE);
//Check if the shared preference key exists.
//This way, you can determine if the fault is here or elsewhere.
if (pref.contains(KEY_FIRST_TIME_ON_APP)) {
return pref.getBoolean(KEY_FIRST_TIME_ON_APP, true);
} else {
return true;
}
}
Check if you've set your application to allow backup in the manifest android:allowBackup="true".
Set it as false, uninstall and then reinstall the app.
android:allowBackup=“false”
In case that doesn't fix the issue, then try setting the following in your manifest, uninstalling the app and then reinstalling it.
android:fullBackupContent="false"

Save Application Wide Boolean in SharedPreference

I know that this is a common question asked, and I have spent all afternoon trying different solutions that don't seem to work.
I am trying to store a boolean receiveNotifications in SharedPreferences but when I send a notification it still comes through. When I check whether the boolean is set in the activity I set it in, it says that the value is what it should be, but when I call this in my Firebase MessagingService it still allows the notification to come through.
This is my first time using them so if you see the obvious answer thats why.
Storing the Boolean:
// shared preferences
notificationsPref = mContext.getSharedPreferences("notifications", MODE_PRIVATE);
SharedPreferences.Editor editor = notificationsPref.edit();
editor.putBoolean("receiveNotifications", false);
editor.apply();
Checking if Boolean is Set:
// check if they want to receive notifications
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("notifications", MODE_PRIVATE);
Boolean areNotificationsAllowed = sharedPreferences.getBoolean("receiveNotifications", true);
if (areNotificationsAllowed){
Toast.makeText(this, "Send Notification", Toast.LENGTH_SHORT).show();
sendNotification(contentTitle, messageBody);
}
A push message is a Json object, next example is directly from the docs:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
There are 3 types of push messages, notification, data, and both;
//Notification
"message":{
"notification":{
}
}
//data
"message":{
"data":{
}
}
//both
"message":{
"notification":{
},
"data":{
}
}
Each will trigger a different behavior in the app depending if the app is open or not.
Notification: if the app is open the code on the service will be executed, if not the notification is showed by default
Data: Always the code on the service will be executed
Both: f the app is open the code on the service will be executed, if not the notification is showed by default and the data will be available in the launcher activity as extra obtainable from the intent
The Firebase web console will always send "notification" type and if you add data as custom params it will send both.
Your boolean will never be taken in consideration if the app is closed and the notification comes from the web console.
Turns out that no matter what you do Firebase must override whatever you have set in the application. I found this out by instead of sending from the Firebase console, I sent notification from my web server. The notification was stopped perfectly and the Shared Preference worked.
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
prefs = getApplicationContext().getSharedPreferences("notifiactions",
MODE_PRIVATE);
editor = prefs.edit();
/////Assigning a Boolean///////////
editor.putBoolean("receiveNotifications", false);
editor.commit();
//Retrieving Boolean
prefs = getApplicationContext().getSharedPreferences("notifications",
MODE_PRIVATE);
bool = prefs.getBoolean("receiveNotifications", true);
//Try replacing this with your code also
if(bool){
}

Variables don't get changed after going back

I have a boolean variable public static boolean isInDarkTheme but when I try to change the value in my settings activity it only gets changed tempolarily.
I did it so:
if (on) {
//Do something when Switch button is on/checked
MainActivity.isInDarkTheme = true;
} else {
//Do something when Switch is off/unchecked
MainActivity.isInDarkTheme = false;
}
Log.d("DarkTheme", "SETTINGS " + MainActivity.isInDarkTheme);
in my settings the variable is changed but when I go back to my main with the
arrow I created with this:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
picture with this button
it is still the same in the main
but! when I use my software key to get back to the MainActivity it get saved
picture with software back key
Any idea what I can do that it get saved with the other button?
your variable will not be saved and will be collected by garbage collector once the activity is destroyed.
you have to use something like SharedPreferences.
to save the variable
SharedPreferences sharedPrefrences = getSharedPreferences("pref_name", MODE_PRIVATE);
sharedPrefrences.edit().putBoolean("isDarkTheme", true).apply();
to load
SharedPreferences sharedPrefrences = getSharedPreferences("pref_name", MODE_PRIVATE);
// key , default value
boolean isDark= sharedPrefrences.getBoolean("isDarkThem", false);
read about SharedPreferences here
The most likely reason is that both activities are loaded by different class loaders with the effect that the MainActivity you "see" in your Settings activity is a different one than the one you "see" in your other activity. You can find that out by logging the classloader "attached" to the MainActivity by calling MainActivity.class.getClassLoader()

What is the best way to detect whether the objects are saved in javafx desktop application?

I am currently developing a javafx desktop application. It contains two observableList<Item>s and two HashMap<String,Double>s. I am currently develop the menuBar , which contains these menuItem s, i.e. Open, New, Save and Save As.
Consider the case where I have started the desktop application and added a few Item to the observableList<Item>. Then all of a sudden, I want to hit any one of the menuItems listed above. First thing I want to check in my program is whether the current workflow needs to be saved before proceeding to start a new workflow (New menuitem).
I have the following method in place at the moment but I think it looks very clumsy and inefficient.
The method I developed is to set a variable private static final boolean isSaved = false;
And then within the two observableLists, I added a Listener to them:
obslist1.addListener(new ListChangeListener<Item>(){
#Override
public void onChanged(ListChangeListener.Change change) {
isSaved = false;
}
});
The code for obslist2 is identical. And the isSaved variable is set to true only if the user actually presses the Save or Save As menuItem.
I find my method very clumsy and inefficient. Is there a better way to do this?
You can do something like
BooleanProperty saved = new SimpleBooleanProperty();
InvalidationListener savedListener = obs -> saved.set(false);
and then
private void save() {
// save the data...
// mark data as saved:
saved.set(true);
}
with
obslist1.addListener(savedListener);
obslist2.addListener(savedListener);
anythingElseThatMightChangeAndIsImportant.addListener(savedListener);
Your save button and menu item, etc can do
saveButton.disableProperty().bind(saved);

Unable to fetch SharedPreferences

I'm trying to get familiar with using SharedPreferences, by building a simple test app where I store and retrieve user preferences by using a class that extends 'PreferenceActivity'.
The problem is that every time I shut down the app and start it again I'm unable to load the SharedPreferences values that I earlier selected.
In the MainActivity's onCreate method I am first calling a method 'loadPreferences', then creating an ImageView and a button.
I assigned onclick listener to the button that creates and starts a new intent.
...onClick(View v){
Intent intent = new Intent(MainActivity.this, MyPrefsActivity.class);
startActivity(intent);
}
In MyPrefsActivity class I have a ListPreference that has a 'Preference.OnPreferenceChangeListener'.
... {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
imageNumber = Integer.parseInt(newValue.toString());
return true;
}
};
Upon return from MyPrefsActivity to MainActivity in the 'onResume':
protected void onResume() {
super.onResume();
savePreferences();
loadPreferences();
}
private void savePreferences(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("imageNumber", MyPrefsActivity.imageNumber);
editor.apply();
}
private void loadPreferences (){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int imageNumb = prefs.getInt("imageNumber", 0);
switch (imageNumb){
case 0:
imageView.setImageResource(R.mipmap.image1);
break;
case 1:
imageView.setImageResource(R.mipmap.image2);
break;
case 2:
imageView.setImageResource(R.mipmap.image3);
break;
default:
imageView.setImageResource(R.mipmap.image4);
}
}
When 'loadPreferences' is called for the first time upon startup, 'imageNumb' allways has a value 0, instaed of the value that I assigned to on previous run in method 'savePreferences'.
I noticed that after startup when I enter 'MyPreferencesAction' for the first time and open the ListPreferences, the checkbox that I selected on the last run is already selected for me. It seems like my selection is saved but when I try to load SharedPreferences am I messing up something???
You have to save your preferences in onPause event. Right now you are saving it in onResume when values you want are no longer there.
#Override
protected void onPause(){
super.onPause();
savePreferences();
}
#Override
protected void onResume() {
super.onResume();
loadPreferences();
}
There is another issue with your code. You are saving preferences in MainActivity, but you are changing them in MyPrefsActivity. That will not work. You have to save changes to the preferences in MyPrefsActivity, use above load/save pattern in there too. If you don't have any preference changes happening in MainActivity, you can safely omit calling savePreferences from it.
Depending on MyPrefsActivity declaration calling MyPrefsActivity.imageNumber from MainActivity may not be safe, you will have to change that code too. Like I said, most likely you don't need it at all in MainActivity (if you saving are only preferences values that are set in MyPrefsActivity) and that should be part of MyPrefsActivity.
Also Preference.OnPreferenceChangeListener is probably redundant since it's main usage is to be invoked when the value of this Preference has been changed by the user and is about to be set and/or persisted. This gives the client a chance to prevent setting and/or persisting the value.
I realized there was a lot of needless complexity in my code. So I got completely rid of the method savePreferences(). Instead i simplified the PreferenceChangeListeners method onPreferenceChange(...):
This seems to me to be the most simplest way to update SharedPreferences when using PreferenceActivity.
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.getEditor().
putInt("imageNumber", Integer.parseInt(newValue.toString())).apply();
return true;
}
Now I save the SharedPreferences manually, only when 'onPreferenceChange' is called. Not on 'onResume', 'onStop', 'onRestart' or on 'onPause'.
Please inform me if this is a bad way to change SharedPreferences.
Quoting Dalija Prasnikar: "reference.OnPreferenceChangeListener is probably redundant since it's main usage is to be invoked when the value of this Preference has been changed by the user and is about to be set and/or persisted. This gives the client a chance to prevent setting and/or persisting the value."
If you understood you correctly Dalija, there is a 'onPreferenceChange(...)' like method that does the job but does not have a boolean return value but void? I was not able to find any examples, could you please show or point to an examle?

Categories