Can't get onSharedPreferenceChanged() to work - java

I wanna display a dialog when the user selects a specific item from a ListPreference in my preferenceActivity. But, I cannot get the onSharedPreferenceChanged() to work. I've put a Toast in the beginning of the method, and it does not show, so the method doesn't even run through, why is this?
Here's my code: (Thanks)
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Toast.makeText(Preferences.this, "prefs Changed", Toast.LENGTH_SHORT)
.show();
if (key.equals("boolean_ad_type")) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String value = sharedPreferences.getString("boolean_ad_type", "");
if (value != null && value.equals("Pop-up Ads")) {
Toast.makeText(Preferences.this, "Pop-up Ads Selected",
Toast.LENGTH_SHORT).show();
}
}
}
And do I need to implement it in the activity like this? (I've tried with and without, no difference)
public class Preferences extends PreferenceActivity
implements OnSharedPreferenceChangeListener {

onSharedPreferenceChanged not fired if change occurs in separate activity?
public class MyActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}

you have to set a click listener for that specific preference you want to show the dialog in your onCreate
PreferenceScreen ps2 = (PreferenceScreen) findPreference("ic_vol");
ps2.setOnPreferenceClickListener(this);

Related

how to show one time toast messages in android studio

I wanted to add a `toast message` when clicked on a button and I added it. Now I want show it only **one time**, that means the toast message will **not show again** if clicked on the button after the first time **also after a restart of app**.
Please help me!
You can do it with SharedPreferences that you store in another class like Utility.java:
public class Utility {
public static SharedPreferences preferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
public static Boolean hasSendToast(Context context) {
return preferences(context).getBoolean("Toast", false);
}
public static void setSendToast(Context context, Boolean bool) {
preferences(context).edit()
.putBoolean("Toast", bool).apply();
}
}
And use it with your Toast inside the onClickListener in your MainActivity.java like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(v -> {
if (!Utility.hasSendToast(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "My Toast", Toast.LENGTH_SHORT)
.show();
Utility.setSendToast(getApplicationContext(), true);
}
});
}
}
You might want to look into https://developer.android.com/training/data-storage/shared-preferences. After the first click write a boolean into shared preferences to indicate the first click has happened. Next time the user clicks the button make sure to check if that boolean has been set and don't show the toast if that's the case.
You can use a boolean flag and store the value using Shared Preference.
btn.onClickListener {
if(!getToastShownStatusFromSharedPreference()) {
showToast()
changeToastShowsStatusToSharedPreference()
}
/* other operations */
}
Yes you can do that with SharedPreferences which is a pref manager in android. You can follow the below process:
Declare a boolean as like isFirstTime = true.
On the click of the button check boolean status, and if its true then fire the toast message and make isFirstTime = false.
That's it.

How to make `onResume` only be called when the activity comes to screen and not by other methods calling it

I have a situation with onResume() method and I don't know how to solve it.
conssider the following code:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
Log.d("tag", "onCreate");
}
#Override
protected void onResume() {
super.onResume();
//do something only when everytime the activity comes to screen
Log.d("tag", "onResume");
}
private void myMethod() {
this.onResume();
}
}
If we asume that myMethod will definitly be called, I don't want to let onResume() to execute //do something only when everytime the activity comes to screen. I should note that myMethod is a fixed method and cannot be changed.
PS:The reason that I am asking this question is that I have a simillar situation with PermissionDispatcher library with android 6 and I want to call a "risky permission" in the onReume() method but if the user denies the permission, it will call the onReume() again, and since the permission required task is in the onResume(), the permission will be denied again and cauases an inifite loop
could anyone give me a suggestion?
UPDATE: here is the permissionDispatcher library and the issue that is related to my problem
verify this method Already Executed or not simply in if Condition
Bool a=true;
#Override
protected void onResume() {
super.onResume();
//do something only when everytime the activity comes to screen
if(a==true)
{
//your Actions
}
else if(a==false)
{
//do nothing
}
}
Use SharedPreferences in onResume
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean firstStart = settings.getBoolean("firstStart", true);
if(firstStart) {
//do something only when everytime the activity comes to screen
Log.d("tag", "onResume");
//display your Message here
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstStart", false);
editor.commit();
}
}

On Preference change listener - after click run twice

I have in my app preference activity with EditTextPreference and I added this, to detect, when the text in edittext is changed. All works, except for that, the code runs always twice... I tryed to add System.out.println("now"); to proove if the code runs twice, and it writes "now" two times...
Here is the code:
SharedPreferences.OnSharedPreferenceChangeListener myPrefListner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.admin_activity);
myPrefListner = new SharedPreferences.OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
switch(key) {
case "prefAddUser":
EditTextPreference connectionPref = (EditTextPreference) findPreference(key);
String jmeno = connectionPref.getText();
System.out.println("now");
add_user(jmeno); //custom method to add user to MySQL database
Toast.makeText(getApplicationContext(), "add user", Toast.LENGTH_SHORT).show();
connectionPref.setText("");
break;
}
}
};
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(myPrefListner);
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(myPrefListner);
}
I don't know what to do with this weird problem...
What should I do?
Calling OnSharedPreferenceChangeListener in anonymous class makes it become the target of garbage collection.
As soon as you leave the current scope and can cause unregisterOnSharedPreferenceChangeListener() to be call on a null context.
Implement it in the class scope like this:
public class SettingsActivity extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "pref_syncConnectionType";
...
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(KEY_PREF_SYNC_CONN)) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
Read the next tutorials for further explanation:
1. Good So answer on the subject
2. Official documentation here

How can i update my activities after preference changes immediately?

I want to update my activity immediately after a user changes a setting like language or time format.
Here is my code:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
public static final String HOUR_FORMAT = "hourFormat";
public static final String LANGUAGE_CHOICE = "languageSelection";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("hourFormat")) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(Boolean.toString(sharedPreferences.getBoolean(key, true)));
}
else if(key.equals("languageSelection")) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, "English"));
}
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}
This is preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="hourFormat"
android:title="#string/hour24"
android:summary="#string/hour24Explanation"
android:defaultValue="true" />
<ListPreference
android:key="languageSelection"
android:entries="#array/languageValues"
android:summary="#string/languageSelection"
android:entryValues="#array/languageValues"
android:title="#string/language" />
</PreferenceScreen>
This only works, if i restart the app. However I want to update it immediately just after the change? (If you want, I can provide other source codes in my app, I know there are lots of resources but I couldn't get this thing working.)
I also think I don't really understand the xListener concept in Java. I read about it a lot but can you clarify or provide additional links to me.
Thanks, in advance.
You need to receive the system triggers when the user changes them. To do this, you need to have a class to receive the information, for example for the Time change, put this class in the main Activity class:
private final BroadcastReceiver timeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED) ||
action.equals(Intent.ACTION_TIMEZONE_CHANGED))
{
doStuffYouNeedToDo();
}
}
};
Write a method doStuffYouNeedToDo in the Activity which does whatever you need to when the time or timezone is changed. To make sure it is called, put this in your class:
// For intent filter for catching timezone etc changes
private static IntentFilter timeChangeIntentFilter;
static {
timeChangeIntentFilter = new IntentFilter();
timeChangeIntentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
timeChangeIntentFilter.addAction(Intent.ACTION_TIME_CHANGED);
}
and this in onCreate:
registerReceiver(timeChangedReceiver, timeChangeIntentFilter);
And to stop it when the Activity stops, put this in onDestroy:
unregisterReceiver(timeChangedReceiver);

SharedPreferences putBoolean on change won't work

I have an if loop when a chebkox in sharedpreferences changed status. But I'm not able to set putBoolean("blabla", false); when the status changed.
For example: User hits checkbox, CB gets checked, if says uncheck it but it won't uncheck.
My Code:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("cbSaveUsername")) {
SharedPreferences.Editor SFEdit2 = sharedPreferences.edit();
SFEdit2.putBoolean("cbSaveUsername", false);
SFEdit2.commit();
}
}
Can anyone tell me my mistake?
Edit: It looks like it works programatically but the tick is still in the box :o Where could be the mistake? I use it like Gunaseelan postet
Try to use onPause() and onResume() methods.
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
For more details onSharedPreferenceChanged not fired if change occurs in separate activity?

Categories

Resources