Android - Language change when clicking back - android

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

Related

Android SavedPrefrerences loading?

I am trying to make an app(http://pastebin.com/uWkP6XNY) that when you press a button, creates a custom sms message. The user can go to a second activity (http://pastebin.com/MK2NPV5R) thats full of edit-texts that when saved, will bring back strings to be used to change the custom sms.
The issues I am facing is how I initalize my variables with whats in savedpreferences. I put this in my onCreate method.
smsintroduction = (sp.getString("intro", "")); //these are both strings initalized at the top
smsbody = (sp.getString("body", ""));
On start up, since it can't get "intro" from the dictionary, it goes to a null string. I want to be able to use my save() function in my second activity to save, which I Think I already do, but be able to change my two strings above.
I put the code above to set the strings in a method that completes the finalized textbody, but it keeps giving me emptystrings.
The only thing that gets created is "!", as shown in finishedtext().
It looks like in your MainActivity in onCreateOptionsMenu you are overriding the sp member previously set in onCreate with
sp = getSharedPreferences("prefs", 0);
Try removing that line or setting those shared prefs to a different instance member.

Best way to backup user's inputs dealing with orientation changes

I am developing a simple apps that allow users to post articles on a website.
It's just a simple form with inputs for title et text and a send button.
To do this, I used a FragmentActivity with a Fragment called ArticleFragment inside.
I've read everywhere that the best way to save user's inputs was to override onPause() in the fragment, and to restore them in the onCreateView().
#Override
public void onPause() {
Log.i(TAG, "Pausing fragment");
Log.i(TAG, "Saving edits");
// Sauvegarde des saisies
EditText titreEdit = (EditText) getActivity().findViewById(R.id.titre_saisie);
EditText texteEdit = (EditText) getActivity().findViewById(R.id.texte_saisie);
String titre = titreEdit.getText().toString();
String texte = texteEdit.getText().toString();
SharedPreferences settings = getActivity().getPreferences(0);
Editor editor = settings.edit();
editor.putString("titre", titre);
editor.putString("texte", texte);
editor.commit();
Toast toast = Toast.makeText(getActivity(), R.string.article_enregistre, Toast.LENGTH_SHORT);
toast.show();
super.onPause();
}
As you can see, each time the activity is paused, a Toast is shown to inform the user that inputs have been saved.
That's what I wanted. But whenever the user changes the orientation of the screen, the popup is shown again (because Activity is paused, then destroyed) and this may annoye the user.
I tried to add android:configChanges="orientation" in the Manifest, but I think this is not the best way to deal with this issue.
I also tried to make a solution with onSaveInstance() but I do not understand how it works : sometimes onSavedInstance is null, sometimes not.
With all this, the main question is what is the best way to save user inputs, with orientation changes and back button, and where to restore what was saved.
Thank you!
Check if input values are empty in onBackPressed() and onClick of whatever button that takes the user to Home and display appropriate Toast message
Add android:configChanges="orientation"to manifest file.
Override onConfigurationChanged. Before you call super.onConfigurationChanged save the data.
If you have different layout files for portrait and landscape you have to remove all the views and setcontentview and initialize them(just like what you do on create ) after all these you can restore the data
I don't quite follow your logic. Lets see ... You have two edittext fields and save button, when user changes screen orientation on destroy you can save input in shared preferences or in Bundle and when onCreate() starts you can check if values are not empty and then show toast that there is a draft. If user hits back button you can also save input and display toast, if he/she hits send you just send input, right ?

get and set listPreference from another activity not working

I'm trying to get and set a listPreference value from different activities and it's not working.
When I read and write it from my main activity, it only keeps whatever I write, so I'm assuming that I'm not targeting the listPreference correctly when I'm out of the activity because it's working inside my preference activity no problem.
I've seen some references on the developer website to CharSequence with getValue and getEntryValues but I haven't had luck getting them to work correctly either.
Here is my code for clicking a button and setting the listpreference value then it launches an intent to switch activities:
Main Activity, attempting to set the value of the listpreference to the first index value;
SharedPreferences settings = getSharedPreferences("PreferenceXML",
MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("ListPreferenceInXML", "1");
editor.commit();
String levelCheck = settings.getString("ListPreferenceInXML","1");
In my next activity I call read the value on launch to see which listPreference is active and it is always the number I write from the mains activity listed above. The problem is when I goto the actual Preference activity and it doesn't match or update when I change it on the ListPreference and launch the same activity from there (it still reads the value I set from the Main activity button)
code as follows for activity trying to read ListPreference:
SharedPreferences settings = getSharedPreferences("PreferenceXML",
MODE_PRIVATE);
Toast.makeText(this, settings.getString("ListPreferenceInXML","1"), 1000).show();
So I finally figured it out, the problem was with the way I was calling the preferences. Instead of calling the preferences like this, in both cases;
SharedPreferences settings = getSharedPreferences("PreferenceXML",
MODE_PRIVATE);
Call them like this:
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
I'm not sure if there is a step missing out of the first way of calling the preferences but this 2nd way worked like a champ.

Showing preference screen first time app is run and related questions

I have an app with 2 activities, the preference and the main activity, I need the preference screen to show first time the app is run so the user can do some configuration. I have checked through the answers on this topic and they don't seem very clear but I gather it has to do with checking that there are sharedpreference file is empty.
Can someone please give me a code to sort this out and on which activity would I put the code?
Also I am still in the developing stage so I already have my preferences setup how do I undo this?
Thanks in Advance
1) When your main activity starts check a boolean preference with the default set to false. If it is false, launch your preference activity, if it is true then you know you have saved it to be true!
SharedPreferences prefs = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
boolean haveWeShownPreferences = prefs.getBoolean("HaveShownPrefs", false);
if (!haveWeShownPreferences) {
// launch the preferences activity
} else {
// we have already shown the preferences activity before
}
2) In your preferences activity save the same boolean preference with a value of true in onCreate
SharedPreferences prefs = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putBoolean("HaveShownPrefs", true);
ed.commit();
I assume that you're running an emulator, when you start the emulator you have the choice to "wipe saved data" when you start it so it will be like you started it as if you just started the application. Alternatively, you can go into settings -> Applications -> You app -> Wipe data.
In regards to your coding solution, I don't have anything handy at the moment, but what you should do is start your main activity, run a procedure/function to check if the sharedpreference file is empty, and if it is start the preference activity, otherwise run your main activity. Alternatively, instead of checking for the file to be empty, you could see if a value that you are looking for user input (for example UserID) is null or not. If that value isn't null that means that the application can continue.
I've sorted this out with this bit of code in my main activity
if (prefs.getString("edittextpref", null) == null)
{
startActivity(new Intent(this, Preferences.class));
return;
}
}
It just checks if one of your values is empty but you need to put this at the bottom of onCreate or else when you go back to the main page it will be blank.
I am doing something like this. And its works for me.
String path = "//data//data//"+this.getPackageName()+"//shared_prefs//feedbackpref.xml";
boolean exists = (new File(path)).exists();
if (exists) {
introWindowNavigate=false;
}

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

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).

Categories

Resources