Answer the question
In order to leave comments, you need to log in
How to make a normal one-time restart of the activity without looping the program when changing the android locale?
In my application, I am trying to change the runtime language, that is, in the process of working. I already asked a question, but no one answered it, so I continued to further deal with this question on my own.
The task is extremely clear to make the application fully support several languages: in order to re-create the activity with a new language on the fly, and then the selected language is saved in the application settings, and this saved language is used on subsequent launches.
What I have done so far:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
String countryCode = data.getStringExtra(CountrycodeActivity.RESULT_CONTRYCODE);
String lang = "en";
switch (countryCode) {
case "English":
lang = "en";
break;
case "Deutsch":
break;
case "Русский":
lang = "ru";
break;
case "Español":
break;
}
Toast.makeText(this, "Your native language is:" + countryCode, Toast.LENGTH_LONG).show();
changeLang(lang);
}
}
private void changeLang(String lang) {
if (lang.equalsIgnoreCase(""))
return;
Locale myLocale = new Locale(lang);
saveLocale(lang);
Locale.setDefault(myLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
config.locale = myLocale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
}
private void saveLocale(String lang) {
String langPref = "Language";
SharedPreferences prefs = getSharedPreferences("def_loc", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(langPref, lang);
editor.apply();
}
@Override
protected void onStart() {
sp = getSharedPreferences("def_loc", 0);
String strLocal = sp.getString("def_loc", "en");
changeLang(strLocal);
super.onStart();
}
Answer the question
In order to leave comments, you need to log in
Of course there will be looping. In the changeLang() method, you launch an activity. It turns out that after the launch of the activity, it launches another one and so on ad infinitum.
You run the changeLang(strLocal) method in onStart() , which, regardless of whether the required locale is the requested one, restarts the activity. You have an endless loop.
Add a branch to changeLang(String) if with a check for the current locale, if it matches the requested one - just exit the method.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question