Android - Determine if a Preference has changed, after user accesses PreferenceActivity - android

I'm making a fairly basic game. In my preferences, there's an option to change the difficulty setting. I'd like to be able to somehow, in the main activity that called it, sense if they've changed the difficulty. (And then restart the game)
I'm having difficulty because of how the preference activity is handled asynchronously. If I add logic to check the value before and after sending the intent to my PreferenceActivity (from a menu selection), it really doesn't work...
Can someone point me in a proper direction as to either how to serialize a chunk of code normally handled asynchronously, or have an idea of how to sense preferences changed? Is there a listener class hidden somewhere?
For posterity's sake, here's the code handling the intent and how I'm failing. (snippet, from inside menu onOptionsItemSelected, inside a switch)
case R.id.menuOptions:
String currentDifficulty = preferences.getString("difficulty","problem!");
Intent i = new Intent(this, prefs.class);
startActivity(i);
if (currentDifficulty.equals(preferences.getString("difficulty","problem!")))
return true;
else doNewGame();
return true;

Android allows you to register a preference changed listener. Here's a quick example:
public class myClass implements OnSharedPreferenceChangeListener
{
private SharedPreferences settings;
settings = PreferenceManager.getDefaultSharedPreferences(this);
settings.registerOnSharedPreferenceChangeListener(this);
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
// Process it here
}
}

OnPreferenceChangeListener You can use it to very easily listen for preference changes.

The OnPreferenceChangeListener is a good idea, but you could also start your preference activity using startActivityForResult(). Your activity is then notified in onActivityResult() after the preference activity returns (you should override it to handle preference changes).

Related

Passing data from MainActivity to sub-Activity when sub-Activity is opened through an Adapter?

So my title may be hard to follow, but I'll try to clarify and expand on what my issue is below.
I currently have an app that starts its life as a MainActivity with multiple Fragments sitting in a ViewPager.
In the MainActivity, I have Android In-App Billing V3 (library) setup so that the user can pay to remove ads. This works just fine in the MainActivity but my issue arises when moving to another Activity.
The first Fragment the user is presented with upon launching the app, contains a RecyclerView with an ArrayList of items. To get to a sub-Activity from the MainActivity, the user presses a button on one of the items in the RecyclerView, which means that the Intent data used to change Activities is contained within the RecyclerViewAdapter.
My issue is that once my app knows that the user has paid to remove ads, I want the app to also remove ads in all sub-Activities as well.
I don't know how to pass this info (that the "Remove Ads" in-app has been purchased) from Activity -> sub-Activity, when sub-Activity is launched through the RVAdapter instead.
So my question is: How would I pass data from MainActivity -> RVAdapter -> Sub-Activity?
Or is there an even better, more efficient way of passing this data along without using Intents? Do let me know!
Did my description of the issue make sense? I hope so! Otherwise let me know how I might clarify it! If you need me to paste in any code, let me know as well.
Thanks for any of your help!
you can use EventBus (greenrobot) nice library for send event this linke
to send evnts
after add library put below method to your main activity:
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event)
don't forget about Register and unregister subscriber, do it like this :
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
finally post your event from everywhere like your subactivity :
EventBus.getDefault().postSticky(new MessageEvent());
Notice:I add postSticky(); to cache data on memory ,Then the sticky event can be delivered to subscribers or queried explicitly.
better solution
but i think you can save value in Sharedpreferences after purcahse:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,
MODE_PRIVATE).edit();
editor.putBoolean("pay", true);
editor.apply();
then check this valu every Activity on onCreat method
to show adds or don't
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
pay = prefs.getBoolean("pay", false);
if (pay) {
show();
}else dontShow();

SharedPreference: OnSharedPreferenceChangeListener not working

Here's my use case.
The PreferenceActivity provides a selectable list of themes. When a user selects a particular theme from the list, I want the effect to take place immediately.
As of now, the change of theme affects all new activities that are launched but it does not affect the currently visible PreferenceActivity and activities on back stack.
To overcome this, I decided to implement a Sharedpreference change listener which on change would clear all old activities from the backstack and restart the same class with the modified theme.
Here's what I tried.
SharedPreferences.OnSharedPreferenceChangeListener spChanged = new
SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
Intent newIntent = new Intent(Settings.this,Settings.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
}
};
I tried simple log message like Log.e("change", "pref changed");
But it seems, this listener is simply not listening for changes.
Register it with SharedPreferences.registerOnSharedPreferenceChangeListener.
Also, keep in mind that the listener is kept in a WeakHashMap. This means that you cannot use an anonymous inner class as a listener, as it will become the target of garbage collection as soon as you leave the current scope. So make your listener an instance variable of your activity or make the activity itself implement the listener.

Android - Language change when clicking back

I have this settings section where I allow users to change the languages displayed within the app. When the user chooses a different language, the activity is reloaded so that the change of language can be applied. But the problem is, when the user clicks back right after changing the language, the language shown in the background activity is still the same.
So my question is, what should I do to apply the change of language when I get back to some activity on the background? I suppose I should do something to detect the change in onResume method, but I'm not sure what it is. If you have any suggestions, please let me know.
Thank you.
After several attempts, I have found the solution to my problem. On my onCreate method, I get the SharedPreferences that contains the value of current language, and get the current language:
SharedPrefrences languagepref = getSharedPreferences("language",MODE_PRIVATE);
String language = languagepref.getString("languageToLoad", Locale.getDefault().getDisplayLanguage());
Then, in my onResume method, I assign the value of the above mentioned variable language to a local variable, and update the value of language. Then I compare these two variables - if they are different, I will destroy the current activity and start another:
#Override
public void onResume(){
super.onResume();
String oldLanguage = language;
language = languagepref.getString("languageToLoad", Locale.getDefault().getDisplayLanguage());
if (!oldLanguage.equals(language)){
finish();
startActivity(getIntent());
}
}
And voila, that did the trick!
I would suggest using SharedPreferences. You can store a lang key with the associated value in there and update it when necessary. In your onResume() methods you can get the lang value and then populate views according the value stored.
SharedPreferences sharedPreferences;
sharedPreferences = this.getSharedPreferences("MyActivity", Activity.MODE_PRIVATE);
String lang = sharedPreferences.getString("lang", "en-GB");
SharedPreferences.Editor editor;
editor = sharedPreferences.edit();
editor.putString("lang", "en-US").commit();
That's the basics you need to get going.
Have you tried restarting the Activity after the change is done ?
You can Simply use
finish();
startActivity(getIntent());
to refresh an activity whenever it detects a preference change.
The built in back pressed function does not refresh the code,so do this after u you change the language.
#Override
public void onBackPressed()
{
//new MainActivity();
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
}
and in Main Activity class do this
public MainActivity() {
//1- This code is responsible for updating the change of all Strings from a language to another
//it will be called every time this activity is instantiated (da,since it is a constructor) , or when this activity gets
// called by an intent.
//2- Every String inside this Activity(ever fragment inside it ) will also be under the effect of change of language
LocalUtils.updateConfig(this);
}
Please review the following answer and add this to it. To get a full answer written by Roberto.B and LarsH:
Changing Locale within the app itself

PreferenceFragment - Difference between getPreferenceManager() and getPreferenceScreen()?

I've implemented my own PreferenceFragment subclass (detailed here), and want to listen for preference changes within it. PreferenceFragment provides you with two ways of doing this:
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
and
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
Which one should be used? What's the difference? I don't really understand the distinction made in the Android docs.
The core difference is in their names, PreferenceManger grants access to different functionalities to the developer for managing SharedPreferences, such as retrieving the map of current preference values or setting user preferences. to their default values. PreferenceScreen handles displaying a screen of user preferences, so that the user can assign values to them. Sometimes this means displaying a list item on a screen with other preferences, that opens another screen with more preferences when clicked, as is the case when PreferenceScreens are nested.
Your question implies that you think there is a difference between what PreferenceManager.getSharedPreferences() and PreferenceScreen.getSharedPreferences() does, but according to the source code, they are identical.
PreferenceScreen:
public SharedPreferences getSharedPreferences() {
if (mPreferenceManager == null) {
return null;
}
return mPreferenceManager.getSharedPreferences();
}
So the PreferenceManger and PreferenceScreen are different entities, but the SharedPreference those method return should be the same object, since PreferenceScreen calls the method from PreferenceManager. I hope that is the answer you've been seeking.
If you have a choice, go with PreferenceManager.getSharedPreferences(), it's more obvious and one fewer method call internally.
Fun fact:
PreferenceFragment:
public PreferenceManager getPreferenceManager() {
return mPreferenceManager;
}
public PreferenceScreen getPreferenceScreen() {
return mPreferenceManager.getPreferenceScreen();
}
The first one gets the shared preferences from the PreferenceManager. The second one, from the PreferenceScreen, that inherits this method from Preference class.
I think this is not a functional difference, because both return probably the same instance of the SharedPreferences objects, but I think it's clearer to use the first one (using PreferenceManager instead of PreferenceScreen).
PreferenceScreen see domentation here
PreferenceScreen class can appear in two places:
When a PreferenceActivity points to this, it is used as the root and
is not shown (only the contained preferences are shown).
When it appears inside another preference hierarchy, it is shown and
serves as the gateway to another screen of preferences (either by
showing another screen of preferences as a Dialog or via a
startActivity(android.content.Intent) from the getIntent()). The
children of this PreferenceScreen are NOT shown in the screen that
this PreferenceScreen is shown in. Instead, a separate screen will be
shown when this preference is clicked.
PreferenceManager see documentation here:
Difference :
getPreferenceManager () returns the current preference manager associated with the fragment.
getPreferenceScreen () returns the root PreferenceScreen i.e. root preference screen used in the fragment from preference xml file(preferences.xml).

Kill and destroy activity

The first screen of my application is a login screen, so I used the method finish () after user have logged. However when i return the application I would like to be already logged. I tried to use onDestroy (), but without success.
It'll be better if you implement your logic otherwise. The first screen in your application can be HomeScreenActivity in which you'll check if the user is logged and start LoginActivity if needed.
public class HomeScreenActivity extends Activity {
/* some declaration */
public void onCreate(Bundle savedInstanceState) {
/* some other stuff */
if (!userIsLogged()) {
Intent intent = new Intent(this,LoginActivity.class);
startActivity(intent);
}
}
}
You have to use SharedPreferences.
See Data Storage on Android Developer
You might want to have a look at the Activity Life Cycle... Furthermore SharedPreferences can be used to save username/login details but im of the understanding that they can be accessed by any application, so be careful what you put there.

Categories

Resources