Get a string from another locales string.xml file - java

Example: I want to get to get string "about_message" from "en"'s locale file (strings.xml) but currently using locale "de" inside the app and when referencing (R.string.about_message) returns the de string value obviously.
Is there a method to do this?

Let's assume you have a <string name="hello">Hello</string> inside your values/strings.xml, which also has a translation (say French) inside values-fr/strings.xml <string name="hello">Bonjour</string>. Normally you'd do the following:
String s = getResources.getString(R.string.hello); // s: "Hello"
To get the "Bonjor" string you'd have to create an alternative resources instance and use it to access the French string by changing to appropirate Locale:
Resources normalResources = getResources();
AssetManager assets = normalResources.getAssets();
DisplayMetrics metrics = normalResources.getDisplayMetrics();
Configuration config = new Configuration(standardResources.getConfiguration());
config.locale = Locale.FRENCH;
Resources frenchResources = new Resources(assets, metrics, config);
String s = defaultResources.getString(R.string.hello); // s: "Bonjour"
Hope this helps.

Related

Get ringtone - english name

I want to get the ringtones of a phone, but see only the english (non-localized version).
My theory, was using a ContextWrapper, and set that context locale to en_US and pass that new locale to RingtoneManager.getRingtone() (code based from Set Locale programmatically ):
ContextWrapper cw = new ContextWrapper(context);
Context cc = setContextLocale(cw, "en_US"); // This method was copied from the StackOverflow question above ^^
Ringtone defaultRingtone = RingtoneManager.getRingtone(cc, Settings.System.DEFAULT_RINGTONE_URI);
String sss = defaultRingtone.getTitle(cc);
So, yes, this does not work as expected. Any ideas?
Hope you find what you are looking for with following code snippet:
data class Ringtone(
val _id: String,
val title: String
)
val cursor = RingtoneManager(this).cursor
cursor.moveToFirst()
val list = ArrayList<Ringtone>()
do {
list.add(Ringtone(
cursor.getString(0),
cursor.getString(1)
))
} while (cursor.moveToNext())
Log.i(TAG, "ringtones list=$list")

How to rewrite SharedPreferencesCompat in JavaFX [duplicate]

For example, I have a window with a preference button.
I want to make it so that when user press the preference button and checks his/her appropriate options and press ok, it saves the preference, then when user presses run on the main window, it runs accordingly to preference the user changed on the preference window.
Thank you in advance.
You can use java.util.prefs package. A simple example:
// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
// Preference key name
final String PREF_NAME = "name_of_preference";
// Set the value of the preference
String newValue = "a string";
prefs.put(PREF_NAME, newValue);
// Get the value of the preference;
// default value is returned if the preference does not exist
String defaultValue = "default string";
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"
There are many more examples at java2s.com.
There is a Java Preferences API specifically for this purpose. It lets you store per-user preferences in an easy cross-platform way, while the API itself takes care of where and how to store the data.
public void saveProperties() {
try {
String USER_NAME = "Some name";
String DP_ADDRESS = "Some url";
//create a properties file
Properties props = new Properties();
props.setProperty("User name", USER_NAME);
props.setProperty("Display picture address", DP_ADDRESS);
File f = new File("YOUR_TARGET_FILE_PATH");
OutputStream out = new FileOutputStream( f );
//If you wish to make some comments
props.store(out, "User properties");
}
catch (Exception e ) {
e.printStackTrace();
}
}
You may use java.util.Properties to save your preferences

How do I set text of TextView to a string resource? (Java for android)

I would like to change the text of a TextView component to another text, that I have already created in strings.xml. When the app starts, the text shown is stored in strings.xml, under the name "help0". I would like to set this to the string under the name "help00" programmatically, by placing another "0" at the and of the name. So far I have written this code :
String help = "0";
help = help + "0";
final TextView help = (TextView) findViewById(R.id.help);
help.setText("#string/help" + help);
However, when I run the app the text changes to "#string/help00", instead of the text I have stored under help00 in strings.xml.
How could I fix this problem?
Because You have concatted String resource id with normal String help So its worked as a String. You have to get first resource string from android resource and then need to concat with local String variable, like,
help.setText(getResources().getString(R.string.help)+help);
As I doubt, if you are looking for dynamically String id, You want String resource id with already exist id and '0' append to it then get int resource id from String using..
int resourceId = this.getResources().getIdentifier("#string/help" + help, "string", this.getPackageName());
and then
help.setText(resourceId);
Try this
String help = "0";
final TextView tvHelp = (TextView) findViewById(R.id.help);
String yourString = getResources().getString(R.string.help);
tvHelp.setText(yourString +help)
I believe that strings.xml resource file content cannot be edited during runtime.
now i am assuming u have the following on your strings.xml file
<resources>
<string name="app_name">Application Name</string>
<string name="help0">Text1</string>
<string name="hellp00">Text2</string>
</resources>
if u want to change the text on your TextView (id=#+id/textview) from the value stored as "help0",to value stored in "help00" use the following code:
String text= getString(R.string.help00);
TextView myTextView = findViewById(R.id.textview);
myTextView.setText(text);

How to internationalize error messages when using Hibernate Validator with GWT?

I'm looking for a bit of help on how to internationalize my hibernate validation messages while using GWT, so that it works with both client and server messages.
According to this question, I should put a ValidationMessages.properties file in my class path, or use the following code:
Validation
.byProvider(HibernateValidator.class)
.configure()
.messageInterpolator(
new ResourceBundleMessageInterpolator(
new PlatformResourceBundleLocator("com.mycompany.Messages")))
.buildValidatorFactory()
.getValidator();`
But will this method work on the client side, with GWT code? What should I do to make it work on the client side?
Please check GWT Internationalize.
If you want to internationlize for messages with GWT , check Static String Internationalization and Dynamic String Internationalization.I used GWT ConstantsWithLookup for constant datas (such as Text of Buttons , Text ofLabels ).
And I use GWT Messages for my message datas (such as alerts , warning , confirm , prompt dialogs).
Don't be forget to add configuration at gwt.xml file as below...
<extend-property name="locale" values="en"/>
<extend-property name="locale" values="ja"/>
<!-- set the fallback for locale default Japan -->
<set-property-fallback name="locale" value="ja"/>
........
I used Local en for English and ja for Japanese. I created ListBox for user to choose Locale as they prefer and used Cookie to maintain as user perference. Below is my sample codes for saving locale in cookie to internationalize at next-time open...
public static void initializeLocaleBox(final ListBox localeBox) {
String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName();
if (currentLocale.equals("default")) {
currentLocale = "ja";
}
String[] localeNames = LocaleInfo.getAvailableLocaleNames();
for (String localeName : localeNames) {
if (!localeName.equals("default")) {
String nativeName = LocaleInfo.getLocaleNativeDisplayName(localeName);
localeBox.addItem(nativeName, localeName);
if (localeName.equals(currentLocale)) {
localeBox.setSelectedIndex(localeBox.getItemCount() - 1);
}
}
}
localeBox.addChangeHandler(new ChangeHandler() {
public void onChange(final ChangeEvent event) {
String localeName = localeBox.getValue(localeBox.getSelectedIndex());
Date now = new Date();
long sevenDays = now.getTime();
// seven days
sevenDays = sevenDays + (1000 * 60 * 60 * 24 * 7);
now.setTime(sevenDays);
Cookies.setCookie("locale", localeName, now);
UrlBuilder builder = Location.createUrlBuilder().setParameter("locale", localeName);
Window.Location.replace(builder.buildString());
}
});
}
public static boolean isLocaleJapan() {
String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName();
return currentLocale != null && currentLocale.equals("ja") ? true : false;
}
public static boolean isLocaleEnglish() {
String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName();
return currentLocale != null && currentLocale.equals("en") ? true : false;
}
For changing URL to localize , I converted with GWT as follow..
public static final String getBaseUrl(final int codesvrPort) {
String locale = Cookies.getCookie("locale");
if (locale == null || locale.equals("")) {
locale = "en";
}
String baseUrl = GWT.getHostPageBaseURL() + GWT.getModuleName() + ".html";
if (GWT.getHostPageBaseURL().contains("localhost")
|| GWT.getHostPageBaseURL().contains("127.0.0.1")) {
return baseUrl + "?locale=" + locale + "&gwt.codesvr=127.0.0.1:" + codesvrPort;
}
return "";
}
Here is useful link for you. I am sorry for too many links. Have some useful for you :)
Edit(Suffixing a properties file)
Qouted from this link.
Note: Suffixing a properties file
If you've never dealt with internationalization before, you may be wondering why the _de suffix is appended to German properties file. The suffix _de is the standard language tag for the German language (Deutsch). Languages tags are abbreviations that indicate a document or application's locale. In addition to specifying the language, they can also contain a subtag indicating the region of a locale. For example, the language tag for French-speaking Canada is fr_CA.
In GWT, properties files indicate the locale with a language code suffix (just like Java resource bundles). The exception is the properties file for the default locale. When no locale is explicitly set at runtime, the properties file with no language code suffix is used. For StockWatcher, you've specified the default translation with annotations instead of using a default properties file.

Using an unsupported language in an app [duplicate]

I am aware of Creating a new values directory for the language with the suffix of the language code. For german: values-de or french: values-fr then copy our string.xml into that and translate each entry. And this works based on the Phone Localization settings
I wanted to know if we can bypass the phone setting and and make the user select his required language inside the app?
My requirement is, i want to give a language selection option inside my app, and make the user select the language he wants for the app.. how to dynamically switch between the string.xml (for different languages) ???
thanks in advance
Create method which sets your basic Locale.Lets say
public static void setDefaultLocale(Context context,String locale) {
Locale locJa = new Locale(locale);
Locale.setDefault(locJa);
Configuration config = new Configuration();
config.locale = locJa;
context.getResources().updateConfiguration(config, context.getResources()
.getDisplayMetrics());
locJa = null;
config = null;
}
Now check when user selected Locale.(Here basically I have used menu for language selection).
Configuration config = new Configuration();
String newLocale = config.locale.getLanguage().substring(0, 2)
.toLowerCase();
if ("ja".equalsIgnoreCase(newLocale)) {
// Call above method with context & newLocale
}
// Sequentially you check for Locale & change that.
Check out this post... It is the same thing basically.
Changing Locale within the app itself
Locale appLoc = new Locale("en");
Locale.setDefault(appLoc);
Configuration appConfig = new Configuration();
appConfig.locale = appLoc;
getBaseContext().getResources().updateConfiguration(appConfig,
getBaseContext().getResources().getDisplayMetrics());
If you want to get images according their respective languages,You should create layout folder below like this.First i take the example for custom localization.
Locale appLoc = new Locale("xx");
Locale.setDefault(appLoc);
Configuration appConfig = new Configuration();
appConfig.locale = appLoc;
getBaseContext().getResources().updateConfiguration(appConfig,
getBaseContext().getResources().getDisplayMetrics());
Your layout folder should be layout-xx and your drawable folder also should be drawable-xx.But one thing that when you change the language,you have to refresh the layout.I used in my app, take a button and set the background image.But sometimes images are not changed so i have done like this .
btn.setBackgroundDrawable(null);
btn.setBackgroundResource(R.drwable.yourimage);
It is very easy just follow this link
languageToLoad = "hi"; // your language
locale = new Locale(languageToLoad);
Locale.setDefault(locale);
config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_main);
- See more at: http://www.theappguruz.com/blog/multi-language-support-to-android-app#sthash.eGmzq57K.dpuf

Categories