I have problem.
I have TabActivity with intent tabs.
In my application user can change language in preference settings.
When user change language and application go back to my TabActivity doing this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
finish();
startActivity(getIntent());
break;
default:
break;
}
}
This code run perfectly, because all text is in changed language.
Problem occur, when i restart application. Some texts are not in proper language (are in system default). When i open preference screen once again and back to my TabActivity, texts are all translated.
How can i translate all texts after restart application?
Why when i first run application not all texts are in proper language?
Im sorry for my English, i hope u understand what i mean and help me. Thank you.
This is code from preferenceActivity when saving:
String lang = preferences.getString("Language", "");
Configuration config = new Configuration();
if (!TextUtils.isEmpty(lang))
config.locale = new Locale(lang);
else
config.locale = Locale.getDefault();
Locale.setDefault(new Locale(lang));
getBaseContext().getResources().updateConfiguration(config, null);
tabActivity:
public class PlanActivity extends TabActivity {
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.app_name);
preferences = getSharedPreferences(Constans.PREF, Activity.MODE_PRIVATE);
edytor = preferences.edit();
String lang = preferences.getString("Language", "en");
Configuration config = new Configuration();
if (!TextUtils.isEmpty(lang))
config.locale = new Locale(lang);
else
config.locale = Locale.getDefault();
Locale.setDefault(new Locale(lang));
getBaseContext().getResources().updateConfiguration(config, null);
setContentView(R.layout.main);
TabHost tabHost = getTabHost();
......... more
And this code is not working properly. I have to go to settings and go back to tabActivity for refresh texts
Are you correctly saving the changes to the SharedPreferences object? The code you provide does not show you using a SharedPreferences.Editor to save your changes.
EDIT: ensure that the preference file you're saving to in your preference Activity is the same one you're opening in your Tab activity (preferences = getSharedPreferences(Constans.PREF, Activity.MODE_PRIVATE);). If your tab activity does not find the preferences you're sure you saved in the preference activity then either your save code is not being called (either use a break point or a log statement to verify) or you are saving to the wrong file.
Related
MyApp testing is multi language change. http://www.androhub.com/android-building-multi-language-supported-app/ After I choose radio button, it changes language in current activity. But when I go back previous activity, it doesn't change language. So, I want to recall onCreate when I click back button. Or How to refresh current activity?
onCreate ()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
txt = (TextView) findViewById(R.id.txt);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioEng = (RadioButton) findViewById(R.id.eng);
radiohi = (RadioButton) findViewById(R.id.hi);
// Initialization
pref = getSharedPreferences("MyPref", Activity.MODE_PRIVATE);
editor = pref.edit();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
String lang = "en"; // Default Language
switch (i) {
case R.id.eng:
lang = "en";
break;
case R.id.hi:
lang = "hi";
break;
default:
break;
}
changeLocale(lang); // Change Locale on selection basis
}
});
loadLocale();
}
changeLocale
private void changeLocale(String lang) {
if (lang.equalsIgnoreCase(""))
return;
Locale myLocale = new Locale(lang); // Set Selected Locale
saveLocale(lang); // Save the selected locale
Locale.setDefault(myLocale); // set new locale as default
Configuration config = new Configuration(); // get Configuration
config.locale = myLocale; // set config locale as selected locale
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); // Update the config
}
saveLocale & loadLocale
private void saveLocale(String lang) {
editor.putString("save", lang);
editor.commit();
if (lang.equals("en")) {
radioEng.setChecked(true);
} else {
radiohi.setChecked(true);
}
}
private void loadLocale() {
String lang = pref.getString("save", "");
if (lang.equals("")) {
radioEng.setChecked(true);
} else {
changeLocale(lang);
}
}
give resultCode when back from current activity, or save configuration, then check configuration on activity resume for language change
I think you should finish the previous activity and recreate it, you can use LocalBroadcast.
You can call onCreate method on back press by handling back press event.
#Override
public void onBackPressed() {
onCreate(new Bundle());
}
If you are using API 11 then use below code and also if above code doesn't work.
Intent intent = getIntent();
finish();
startActivity(intent);
While using the recreate method works by doing
this.recreate()
It was only added in API level 11. If you want to include more devices you can check the API level and implement both the recreate method as well as
Intent intent = getIntent();
finish();
startActivity(intent);
You can use both by making an if statement like...
if (android.os.Build.VERSION.SDK_INT >= 11){
//Code for recreate
recreate();
}else{
//Code for Intent
Intent intent = getIntent();
finish();
startActivity(intent);
}
Intent intent=new Intent(Current_Activity.this,Current_Activity.class);
startActivity(intent);
finish();
instantiate a new intent in your onBackPressed()
Since you are using two activities when you create intent from first activity to second activity the first activity onStop() is called and activity is put to back stack.When you press back button the first activity onCreate() is not called again but onResume() is called and activity is resumed.
So the logic that your are trying to should be done in onResume() such that it will be called every time when you press back button.For more reference check this.
https://developer.android.com/guide/components/activities/activity-lifecycle.html
How to change the language of the app when THE USER selects the language?
I want to do almost this: http://snowpard-android.blogspot.com.br/2013/03/programmatically-change-language-in.html?google_comment_id=z13isbsazkf3hzea504celo5oy3rjzbyevo0k
but instead of changing the language of a textView, I want to create a button with the name of the language, and when the user clicks on it, it goes to a second page already translated. I already created new values with the languages, but can't think about a code that could open another page with those strings. Could anyone help me, plssss?
I would suggest to pass the language name as an intent extra in the first activity and get it in the second activity and update the language accordingly. Consider the following
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// findViewbyId here for button
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, OtherActivity.class);
intent.putExtra("lang", "fr");
startActivity(intent);
}
});
}
}
and in the other activity
public class OtherActivity extends AppCompatActivity {
#Override
private void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String lang = getIntent().getStringExtra("lang") == null ? getIntent().getStringExtra("lang") : "en";
// assuming this is the method you have to call to change the language
changeLang(en);
}
}
Hope this helps.
use localization for achieving this on on click .
String languageToLoad = "hi"; // change your language her this is for hindi
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.main);
I've create an activity to change the locale of the application to load resources of the selected language and I restart the application,moreover I'm keeping an integer value as the app state using sharedpreferences,after setting the locale via the following code,the next time that I open the application the mentioned state does not have the correct value!!!!But,when I remove the language setting there isn't any problem with the state of the application!
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
/*
* Intent refresh = new Intent(this, AndroidLocalizeActivity.class);
* startActivity(refresh); finish();
*/
PrefManager _p = new PrefManager(getApplicationContext(), PrefConfigNames.LANGUAGE_APP_CONFIG);
_p.setStringValue(GeneralPrefKeyNames.LANGUAGE, lang);
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
setResult(RESULT_OK, null);
finish();
I cannot get what happens to sharedpreferences(I've used open source securepreferences (CodeProject article)in this app)
here!!!
Thanks in advance
Edit#1
PrefManager.java
public class PrefManager {
private SecurePreferences _securePreferences = null;
public PrefManager(Context context, String PrefName)
{
_securePreferences = new SecurePreferences(context, PrefName);
}
public void setStringValue(String key, String value)
{
_securePreferences.edit().putString(key, value).commit();
}
}
Edit#2
Something which is so weird is that the state of the application stored in the sharedprefs has the correct value when I debug or run the application from eclipse (debug or run as an android application)!!!but when I rerun it on the phone it has the default value!!!Please help me solve this issue!
Edit#3
I found out that there was a problem with relaunching the application using the following lines,is there another way to relaunch the app without any problem???Or even a better way (to update the language without relaunching the app)?
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
I've tried the following link to achieve the second mentioned approach
Changing locale: Force activity to reload resources?
,but it is not being raised after the following line
res.updateConfiguration(conf, dm);
Thanks in advance
I finally got the solution,in the onPause method I save the currently saved language in the sharedprefs and after changing the locale in the setting activity and returning to the previous activity in the onResume method I compare the newly saved lang with the value kept in the onPause,and if these two are not equal I call recreate method.
#Override
protected void onResume()
{
super.onResume();
SharedPreferences _sPreferences = getSharedPreferences(PrefConfigNames.LANGUAGE_APP_CONFIG,
Context.MODE_PRIVATE);
String resumeLang = _sPreferences.getString(GeneralPrefKeyNames.LANGUAGE, "En");
if (!currentLang.equals(resumeLang))
recreate();
};
#Override
protected void onPause()
{
SharedPreferences _sPreferences = getSharedPreferences(PrefConfigNames.LANGUAGE_APP_CONFIG,
Context.MODE_PRIVATE);
currentLang = _sPreferences.getString(GeneralPrefKeyNames.LANGUAGE, "En");
super.onPause();
};
You should commit() the values
I have implemented an option to select GUI language in my app, but I can't make it refresh the screen when a new language is selected.
The selection is made through a ListPreference so there are 2 problems :
1. Refresh the Preference page in which the language is selected.
2. When the app starts, I set the Locale on the onCreate() of the MainActivity but the MainActivity layout is never getting updated with the new selected Locale. (all other screens are updated so the set code is good).
Here is the code for setting the new Locale :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
String langKey = ctx.getString(R.string.shared_options_select_language_key);
String langDefault = ctx.getString(R.string.shared_options_select_language_default_value);
String appLanguage = preferences.getString(langKey, langDefault);
Locale locale = null;
if (appLanguage.equals(langDefault)) {
locale = new Locale(Resources.getSystem().getConfiguration().locale.getLanguage());
} else {
String[] languageInfo = appLanguage.split("_");
if (languageInfo.length > 1) {
locale = new Locale(languageInfo[0], languageInfo[1]);
} else {
locale = new Locale(appLanguage);
}
}
if (appLanguage.contains(currentLang)) {
return false;
}
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
act.getBaseContext().getResources().updateConfiguration(config, act.getBaseContext().getResources().getDisplayMetrics());
Thank you
Try to refresh the MainActivity after selecting the new Locale
use this to reload the main activity or any activity
public void refrehs_me()
{
Intent intent = getIntent();
finish();
startActivity(intent);
}
Edit : As I can get from your explanation above you save the new locale selected in a shared preference.
Make a new boolean key in the shared preference called (locale_changed) - when a user select a new locale set this key to (TURE) and on the onCreate after setting the new locale check for this key if (TRUE) set it to (FALSE) and reload the activity.
on the second go it will not loop as the key remains (FALSE) until a user change the locale preference again.
The answer would be to position the call to setLocale right before setting the screen content :
setLocale();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I would like the application language to be set according to the user preferences but up till now it doesn't work how I would like it to.
I have set the default values: strings.xml and also values-es with a strings.xml inside in spanish. I have a menu option which brings the user to a Preference activity where he can amon gother things chose the language.
So here are some extracts of the code:
public class Preference extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
......
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
...}
//(......)
//and here I have the listener so when the language pref changes value the locale gets changed.
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("listPref2")) {
String idioma = sharedPreferences.getString("listPref2", "catala");
if ("castella".equals(idioma)) {
idioma = "es_ES";
Locale locale = new Locale(idioma);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getApplicationContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
}
}
So when I change the language it works but then when I come back later or restart the emulator the language gets back to default locale the en_US and the app language gets changed back to default again. What can I do to sort that out?
I know I can get this preference (which I can access to from all my activities) and then each time set up the locale but I find it a bit heavy isn't there a way to do it in a more elegant way?
What I would like to do is if the user sets up the language so when he comes back 2 days later he doesn't have to change the language again.
Any ideas?
OK it may help someone. I have added the folowing to the main activity manifest:
android:configChanges="locale"
Then when the user choses the preferences I have put a confirm button and then this button brings you to main activity that is why the lnagages gets reset.
I have a static class where I have this code to change the locale:
public static void updateLanguage(Context context, String idioma) {
if (!"".equals(idioma)) {
if ("castella".equals(idioma)) {
idioma = "es_ES";
} else if ("catala".equals(idioma)) {
idioma = "ca_ES";
}
Locale locale = new Locale(idioma);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config, null);
}
}
end at every activity I have like 20 of them I call this method before:
setContentView(R.layout.list_event);
With these methods when I rotate the screen the activities don't change the language
here is a link to a blog that helped me:
http://adrianvintu.com/blogengine/post/Force-Locale-on-Android.aspx
I would think that you need to be setting the locale in the MainActivity onCreate method. The same way you are setting it when the onSharedPreferenceChanged method.