How to get String from Localization Strings in Android - android

strings.xml
<string name="funny">Funny</string>
<string name="love">Love</string>
<string name="happy">Happy</string>
<string name="sad">Sad</string>
<string name="film">Film & TV</string>
<string name="accident">Accident</string>
strings.xml (pt)
<string name="funny">Engraçado</string>
<string name="love">Ame</string>
<string name="happy">Feliz</string>
<string name="sad">Triste</string>
<string name="film">Filme e TV</string>
<string name="accident">Acidente</string>
But, when I Use StringArray, then I want only from English String.xml
<string-array name="categories">
<item>#string/funny</item>
<item>#string/love</item>
<item>#string/happy</item>
<item>#string/sad</item>
<item>#string/film</item>
<item>#string/accident</item>
</string-array>

You can do that programatically :
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String languageToLoad = "fa"; // your language
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);
}
}
for more visit link

Try this code for english .
Locale myLocale = new Locale("en");
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
get String Array:
String[] categories= getResources().getStringArray(R.array.categories);

Related

font styles are not Changing neither numbers in android

I'm getting stuck in this for two days i hope i find a solution..
I'm trying to localize my app (Arabic, and English)
the localization mechanism is working fine, the words, layout directions are working well,
However there are two things are not being localized the first one is numbers.
numbers are not being localized to arabic.
the second one is Font style font style are not being localized neither.
BUT it change the font style and number to arabic, only if i reinstalled the app using my USB and the configuration was in Arabic before the installing. here is my code
public static void changeLocale(Activity context, Bundle... bundles) {
MedfastSharedPreferencesHelper sharakehSharedPreference = new MedfastSharedPreferencesHelper(context);
String lang = sharakehSharedPreference.getKey("locale");
Locale locale = null;
if (null == lang) {
locale = new Locale(Resources.getSystem().getConfiguration().locale.getLanguage());
lang = locale.getDisplayLanguage();
if (locale.getDisplayLanguage().equalsIgnoreCase("English")) {
locale = new Locale("ar");
lang = "ar";
} else {
locale = new Locale("en");
lang = "en";
}
} else if (lang.equalsIgnoreCase("ar")) {
lang = "en";
locale = new Locale("en");
} else if (lang.equalsIgnoreCase("en")) {
lang = "ar";
locale = new Locale("ar");
}
sharakehSharedPreference.setKey("locale", lang);
Resources resources = context.getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
Locale.setDefault(locale);
Configuration configuration = resources.getConfiguration();
configuration.setLocale(locale);
configuration.locale = locale;
resources.updateConfiguration(configuration, displayMetrics);
Intent intent = new Intent(context, ((Activity) context).getClass());
if (null != bundles && bundles.length > 0 && null != bundles[0])
intent.putExtras(bundles[0]);
context.startActivity(intent);
context.finish();
}
After researching, android does not support font as resource, so i had do create 6 classes in order to customize my fonts and check weather if the locale is Arabic or english, and depending on the locale i load the font, unlike drawable in android
Hey as Basil Battikhi said, the font does not apply to numbers, But there are some solutions:
1: Create your own custom textView to be able to change things you want.
2: Define this in strings.xml
<string name="number">%1d</string>
and set number to your textView like this:
textCoin.text = getString(R.string.number, it)
3: You can use this code for formating your textView for numbers:
public static String convertEngNumToFa(String number) {
if (AppConstants.FA_LOCALE == DataManager.Language.fa) {
StringBuilder res = new StringBuilder();
try {
for (char _ch : number.toCharArray()) {
if ((int) _ch > 47 && (int) _ch < 58) {
int x = (int) _ch + 1632 - 48;
char ch = (char) (x);
res.append(Character.toString(ch));
} else {
res.append(Character.toString(_ch));
}
}
} catch (Exception e) {
return res.toString();
}
return res.toString();
} else return number;
}

translate string by value in locale

Does android API support translating string resources by value?
I know that I can create multiple XML files for different locale. My problem is that I am getting the values from the server in a "default locale" so, I can't use getString(int).
I want something like getTranslation("myValueInDefaultLocale", "target locale")
There is no efficient way to do what you are asking, but to modify the server. If you can't change server, then you can do this:
Save current locale
Switch to default locale programmatically
Iterate through all string resources looking for specific string
Save ID of the string
Switch back to saved locale
Get translated value of string by ID in desired locale
But this will work really slow. Don't say I didn't warn you.
Here is the code sample:
String translateFrom = "server reply";
Resources res = getResources();
Configuration conf = res.getConfiguration();
Locale savedLocale = conf.locale;
conf.locale = defaultLocale; // set to default locale here
res.updateConfiguration(conf, null);
// iterate through all string resources in default locale
int idTranslateTo = 0;
Field fields[] = R.string.class.getFields();
for (Field field : fields) {
int id = getResources().getIdentifier(field.getName(), "string", this.getPackageName()));
if (translateFrom.equals(res.getString(id)) {
idTranslateTo = id;
break;
}
}
// restore original locale
conf.locale = savedLocale;
res.updateConfiguration(conf, null);
// retrieve translated string from saved locale
if (idTranslateTo != 0) {
String translateTo = res.getString(idTranslateTo);
}

Not able to read strings from region specific folders in Android

I am trying to override locale configuration in my app. But, I am not able to differentiate between language and their regions.
I am trying following code to override the locale.
Getting locale to override.
Example : "de_DE", "de_AT"
public static Locale getLocaleFromString(#NonNull final String locale) {
String[] split = locale.split("_");
if (split != null || split.length > 1) {
String language = split[0];
String country = split[1];
return new Locale(language, language, country);
}
return Locale.getDefault();
}
The structure of my resource folders is:
values/strings.xml (default strings)
values-de-rDE/strings.xml
values-de-rAT/strings.xml
If, I define values-de/strings.xml, application start reading from this folder.
That means locale overriding works in app, but some how android system is not able to read string from region specific folders.
(My device language is english.)
Any help would be really appreciated.
The arguments passed to Location's constructor may be wrong:
The second should be country and the third should be variant.
So getLocaleFromString should like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = getLocaleFromString("de_DE");
res.updateConfiguration(conf, dm);
setContentView(R.layout.activity_main);
}
public static Locale getLocaleFromString(#NonNull final String locale) {
String[] split = locale.split("_");
if (split != null || split.length > 1) {
String language = split[0];
String country = split[1];
return new Locale(language, country);
}
return Locale.getDefault();
}
}

Android Localization from resources

I am currently trying to localize my android app and i have setup everything but it keeps of loading the same string resource whenever i try to change the language.
I have the below string resources
values
values-am
values-om
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String languageLocale = sharedPreferences.getString("SAVED_LANGUAGE_LOCALE", "am");
Log.d(TAG,languageLocale);
String languageToLoad = languageLocale; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
I am also using the code below for selecting the language in a different activity
RadioGroup.OnCheckedChangeListener radioGroupOnCheckedChangeListener =
new RadioGroup.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton checkedRadioButton = (RadioButton)mRadioGroup.findViewById(checkedId);
int checkedIndex = mRadioGroup.indexOfChild(checkedRadioButton);
//AppController languageSetting = (AppController)getApplication();
SavePreferences(KEY_SAVED_RADIO_BUTTON_INDEX, checkedIndex);
mLanguageId = checkedIndex + 1;
languageSetting.setLanguageId(mLanguageId);
switch (mLanguageId){
case 1:
SavePreferencesLocale(KEY_SAVED_LANGUAGE_LOCALE,"en");
mTest = "en";
break;
case 2:
SavePreferencesLocale(KEY_SAVED_LANGUAGE_LOCALE,"am");
mTest = "am";
break;
case 3:
SavePreferencesLocale(KEY_SAVED_LANGUAGE_LOCALE,"om");
mTest = "om";
break;
}
}};
Now the problem is whenever the application started for the first time it loads the correct string resource but when I change the language it keeps the same string resource. that means eg. if the app starts with the values-am string resource when i change it to values-om i still see the values-am strings despite the locale is assigned with the correct value ("om")
Here is something:
String languageLocale = sharedPreferences.getString("SAVED_LANGUAGE_LOCALE", "am");
by **
sharedPreferences.getString(""SAVED_LANGUAGE_LOCALE", "am");
** you dont need string "am". This "am" you need only by .putString()!
Should look like
String languageLocale = sharedPreferences.getString("KEY_SAVED_LANGUAGE_LOCALE");
You need to call the below code on every language selection in onCheckedChanged().
Locale locale = new Locale("Selected language code comes here");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
After setting the Locale, use recreate() to restart the activity.
Intent Refresh and call
Locale locale = new Locale("ar");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_main_category_page);

Android: Language support, spinner options

I have a spinner in my app where the user chooses whether he wants to search by "Contains" "Starts with" "Ends with" or "Equals", The option user selects is stored into a json with other information and sent to server to retrieve results. Now I'm using:
String searchtypeval=searchtype.getSelectedItem().toString();
and adding searchtypeval into my json.
The String-array in the spinner is
<string-array name="search_options">
<item>Starts With</item>
<item>Equals</item>
<item>Ends With</item>
<item>Contains</item>
</string-array>
But now I'm adding language support so in values-fr/strings.xml the string array for that spinner is
<string-array name="search_options">
<item>Commence par </item>
<item>Égal </item>
<item>Se termine par </item>
<item>Contient </item>
</string-array>
Now if the user selects equals in french , Egal is stored into the JSON which of course the server doesn't accept. Is there any way I can make a connection between the french and the english strings.xml? All I can think of now is to use searchtype.getSelectedItemPosition()
and hard code the value into String searchtypeval since I know which option is which position, but this seems very cumbersome, is there any method to solve this issue that is more elegant?
You can send to the server index of a selected element, but this isn't a good way, cause of index is not informated. The better way is sending readable string key to the server. See the following code:
1) create file nontranslatable_string.xml in res/values
<resources>
<string-array name="search_options_keys">
<item>Starts With</item>
<item>Equals</item>
<item>Ends With</item>
<item>Contains</item>
</string-array>
</resources>
2) create your Item class like SpinnerItem
public class SpinnerItem {
public final String key;
public final String value;
private SpinnerItem(String key, String value) {
this.key = key;
this.value = value;
}
public static SpinnerItem create(String key, String value) {
return new SpinnerItem(key, value);
}
#Override
public String toString() {
return value;
}
}
3) fill your adapter with values
String[] keys = context.getResources().getStringArray(R.id.search_options_keys);
String[] values = context.getResources().getStringArray(R.id.search_options);
List<SpinnerItem> items = new ArrayList<SpinnerItem>();
for (int i = 0; i < keys.length; i++) {
items.add(SpinnerItem.create(keys[i], values[i]));
}
spinner.setAdapter(new ArrayAdapter<SpinnerItem>(context, android.R.layout.simple_spinner_item, android.R.id.text1, items));
4) select your value
String valueForSendingToServer = ((SpinnerItem) spinner.getSelectedItem()).key;
UPDATE
Or you can use another way and get neccessary value for any location you use:
Configuration config = context.getResources().getConfiguration();
// Save originla location
Locale originalLocal = config.locale;
// Set new one for single using
config.locale = new Locale("en");
context.getResources().updateConfiguration(config, null);
// Get search_options array for english values
String[] searchOptionsEn = getResources().getStringArray(R.array.search_options);
// Set previous location back
config.locale = originalLocal;
getResources().updateConfiguration(config, null);
String valueForSendingToServer = searchOptionsEn[spinner.getSelectedItemPosition()];
You can reference string resources in the string-array for localization.
<string-array name="search_options">
<item>#string/starts_with</item>
<item>#string/equals</item>
<item>#string/ends_with</item>
</string-array>
and then in res/values/strings.xml:
<string name="starts_with">Starts with </string>
and in res/values-fr/string.xml:
<string name="starts_with">Commence par </string>

Categories

Resources