How to use all available string-arrays from all strings.xml? - android

I am supporting multiple language using values/strings.xml in my app
My current language is ENGLISH.
I have stored icon names in DB, having different languages.
Called following function with icon name in different languages.
More Explanation:[[
Suppose I search "Coffee" then it will return me index =3 because my language is ENGLISH.
Now for next time i search "Kaffee" then it will not found any string like "Kaffee" because my current language is ENGLISH and it is using values/strings.xml file. but i need return index as 3.]]
Need Result : I want to get return index = 3 every time, whatever is my current language.
My thought : Any how I have to search iconName in all of these three languages, not only from current selected ENGLISH language.
Question : So, it is possible to use all supported language's strings to search and get Correct index ?Please give some guidlines!
getIndexOfIcon("Coffee"); --> returns index = 3
getIndexOfIcon("Kaffee"); --> returns index = 0
getIndexOfIcon("Café");--> returns index = 0
public static int getIndexOfIcon(String iconName)
{
String[] predefined_icon_drawable_names;
predefined_icon_drawable_names = mContext.getResources().getStringArray(R.array.predefined_icon_drawable_names_array);
int indextOfIcon = 0;
try
{
indextOfIcon = Arrays.asList(predefined_icon_drawable_names).indexOf(iconName);
if(indextOfIcon<0)
indextOfIcon = 0;
}
catch (Exception e)
{
indextOfIcon = 0;
e.printStackTrace();
}
return indextOfIcon;
}
Following are the strings.xml
ENGLISH Language:/values/strings.xml
<string-array name="predefined_icon_drawable_names_array">
<item>Default</item>
<item>Bath</item>
<item>Brush Teeth</item>
<item>Coffee</item>
</string-array>
GERMAN Language:/values-de/strings.xml
<string-array name="predefined_icon_drawable_names_array">
<item>Standard</item>
<item>Bad</item>
<item>Pinselzähne</item>
<item>Kaffee</item>
</string-array>
SPANISH Language:/values-es/strings.xml
<string-array name="predefined_icon_drawable_names_array">
<item>Por defecto</item>
<item>Baño</item>
<item>Cepillar dientes</item>
<item>Café</item>
</string-array>

Try this way,hope this will help you to solve your problem...
Note : don't try to forget to set your current language after this code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("English Index : "+getIndexOfIcon(this,"en","Coffee"));
System.out.println("GERMAN Index : "+getIndexOfIcon(this,"de","Kaffee"));
System.out.println("SPANISH Index : "+getIndexOfIcon(this,"es","Café"));
}
public static int getIndexOfIcon(Context mContext,String languageCode,String iconName)
{
Locale locale;
if(languageCode.equals("de")){
locale = new Locale(languageCode,"DE");
}else if(languageCode.equals("es")){
locale = new Locale(languageCode,"ES");
}else{
locale = new Locale(languageCode,"EN");
}
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
mContext.getResources().updateConfiguration(config,mContext.getResources().getDisplayMetrics());
String[] predefined_icon_drawable_names;
predefined_icon_drawable_names = mContext.getResources().getStringArray(R.array.predefined_icon_drawable_names_array);
int indextOfIcon = 0;
try
{
indextOfIcon = Arrays.asList(predefined_icon_drawable_names).indexOf(iconName);
if(indextOfIcon<0)
indextOfIcon = 0;
}
catch (Exception e)
{
indextOfIcon = 0;
e.printStackTrace();
}
return indextOfIcon;
}

I am not quite sure what you want to achieve, but i had a similar problem and solved it with this code:
String localized = context.getResources().getString(context.getResources().getIdentifier(mCursor.getString(COLUMN_NAME), "string", context.getPackageName()));
COLUMN_NAME comes out of a query and i just ID'ed my strings with the same names. You might can use this to get what you need.

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;
}

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>

android how can i format a arrayList<String>

i have a problem with format arrayList.I have one parameter it have value
Licence_car:[[คย1453 กรุงเทพมหานคร], [รง2344 กรุงเทพมหานคร], [รน4679 กรุงเทพมหานคร]] (Data is a ThaiLanguage)
I use this parameter to set entry of list preference but it will show like this
I want to delete character is "[" and "]" to make a variable like this Licence_car:[คย1453 กรุงเทพมหานคร, รง2344 กรุงเทพมหานคร, รน4679 กรุงเทพมหานคร] how can i do that?
This is my code set entry to list preference.
#SuppressWarnings("unchecked")
public void showCar(Context context,ArrayList<String> currentCars){
SharedPreferences MYprefs = context.getSharedPreferences(PREFERENCES, PREFERENCE_MODE);
if (null == currentCars) {
currentCars = new ArrayList<String>();
}
try {
currentCars = (ArrayList<String>) ObjectSerializer.deserialize(MYprefs.getString("car_licence_", ObjectSerializer.serialize(new ArrayList<String>())));
//String[] car_list = currentCars.toCharArray;
Log.d(TAG,"Licence_car:"+currentCars);
final CharSequence[] charSequenceCarEntry = currentCars.toArray(new CharSequence[currentCars.size()]);
mCarDefault.setEntries(charSequenceCarEntry);
mCarDefault.setEntryValues(charSequenceCarEntry);
mCarDelete.setEntries(charSequenceCarEntry);
mCarDelete.setEntryValues(charSequenceCarEntry);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I get a preference value in arrayList and format to CharSequence[] for set entry to list preference i think that i do format from this point but i don't know how can do it.
Thank for any answer and sorry for my English.
Hello Developer,
You can foramt your charsequence before storing into array list ,hete i am giving the sample code please use it so here it is-
CharSequence[] charSequenceCarEntry = new CharSequence[10];
int startindex=charSequenceCarEntry.toString().indexOf("[");
int endindex=charSequenceCarEntry.toString().indexOf("]");
CharSequence cs =charSequenceCarEntry.toString().substring(startindex, endindex);
so in your case use it like-
currentCars = (ArrayList<String>) ObjectSerializer.deserialize(MYprefs.getString("car_licence_", ObjectSerializer.serialize(new ArrayList<String>())));
final CharSequence[] charSequenceCarEntry = currentCars.toArray(new CharSequence[currentCars.size()]);
int startindex=charSequenceCarEntry.toString().indexOf("[");
int endindex=charSequenceCarEntry.toString().indexOf("]");
CharSequence cs =charSequenceCarEntry.toString().substring(startindex, endindex);
mCarDefault.setEntries(cs);
mCarDefault.setEntryValues(cs);
mCarDelete.setEntries(cs);
mCarDelete.setEntryValues(cs);
I have solve this problem. I create input variable is type list<string> car_entry; to input a car_licence and output result is [คย1453 กรุงเทพมหานคร] so i will try to change type variable to String and the output is คย1453 กรุงเทพมหานคร as a result of charSequenceCarEntry is Licence_car:[คย1453 กรุงเทพมหานคร, รง2344 กรุงเทพมหานคร, รน4679 กรุงเทพมหานคร].Ok now It is done thank for any answer again. :)

Overriding toString() for Android ListView gives unexpected result

I am working in a project in which I have to show the system's available locales in listview with the following format:
So I've done this in onCreate:
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(getContentView());
String[] locales = getAssets().getLocales(); // all system locale
Arrays.sort(locales); // sort in lexicographic order
final int origSize = locales.length;
// Loc is a class that I've expalined later in this question
Loc[] preprocess = new Loc[origSize];
int finalSize = 0;
for (int i = 0; i < origSize; i++) {
String s = locales[i];
int len = s.length(); // i.e. en_US
if (len == 5) {
String language = s.substring(0, 2); // i.e. en
String country = s.substring(3, 5); // i.e. US
Locale l = new Locale(language, country);
// There are some other logics. I excluded those for simplicity
// and to focus the main problem
preprocess[finalSize++] = new Loc(
toTitleCase(l.getDisplayName(l)), l);
}
}
mLocales = new Loc[finalSize + 1];
// put into another array keeping it's first index empty
for (int i = 0; i < finalSize; i++) {
mLocales[i + 1] = preprocess[i];
}
// put the system default to show it at the first index
mLocales[0] = new Loc("Use System Default", Resources
.getSystem().getConfiguration().locale);
// pass the array to Listview
int layoutId = R.layout.locale_picker_item;
int fieldId = R.id.locale;
ArrayAdapter<Loc> adapter = new ArrayAdapter<Loc>(this, layoutId,
fieldId, mLocales);
getListView().setAdapter(adapter);
}
And the Loc Class is:
public static class Loc {
String label;
Locale locale;
public Loc(String label, Locale locale) {
this.label = label;
this.locale = locale;
}
#Override
public String toString() {
// for the first index, it should show system default
if (this.label.equals("Use System Default")
return (this.label + " (" + this.locale.getDisplayName() + ", "
+ this.locale.getCountry() + ")");
return this.locale.getDisplayName(this.locale);
}
}
Expected Behavior:
________________________________
Use System Default (English, US)
________________________________
বাংলা (বাংলাদেশ)
________________________________
বাংলা (ভারত)
________________________________
English (United States)
....
....
....
But In my case,
________________________________
English (United States)
________________________________
বাংলা (বাংলাদেশ)
________________________________
বাংলা (ভারত)
________________________________
English (United States)
....
....
....
So my question is, why is the text I want to show in the listview in the first index, not showing?
There's a typo in the string you're comparing:
mLocales[0] = new Loc("Use System Default" ...
and
if (this.label.equals("Use Sytem Default") ...
problem in The spelling of System. your are checking Sytem
do
this.label.equals("Use System Default")
instead of
this.label.equals("Use Sytem Default")

How to get ISO Country code in android applications?

I am a new developer on android application. I would like to get the ISO Country code when I pass the mobile number with country code. If I pass the mobile number as 1-319-491-6338, can I get country ISO code as US / USA in android?
I have written the code as follows:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
String mobileno="1-319-491-6338";
Here, where can I pass the mobile number?
Can anybody please help me ?
Thanks in advance
You may not be able to query the country code programmatically via the standard API but you could include a table in your app. Such a table is easily found via Google (e.g. http://countrycode.org/).
Danger Will Robinson!: However, one should ask yourself what question you are trying to answer. Implicit in your question is that assumption that there is a one-to-one mapping between international dialling codes and ISO country codes. This is not true. For example, both the USA and Canada have the international dialling code '1'.
Perhaps think about re-structuring your app's interface. Allow the user to select a country to associate with the phone number but use the table from http://countrycode.org/ to order the most likely candidates at the top?
Had the same problem. Eventually I put all the data in excel and read the excel sheet.
Here is the implementation:
copy-past the country code table from http://countrycode.org/ to Microsoft Excel file.
Save the Excel file as 97-2003 compatible (.xls) in \res\raw\countrycode_org.xls
Download JExcelApi from here
Use the following class to read the file:
public class CountryCodes {
private HashMap mCountryByName = new HashMap();
private HashMap mCountryByCode = new HashMap();;
private ArrayList mCountries = new ArrayList();
public void addCountry(String countryName,String ISO_code,String countryCode){
countryCode = PhoneNumberUtil.normalizeDigitsOnly(countryCode);
Country country = new Country();
country.Name = countryName;
country.Code = countryCode;
country.ISO_code = ISO_code;
mCountryByName.put(countryName, country);
mCountryByCode.put(countryCode, country);
mCountries.add(country);
return;
}
public Country getCountryByCode(String countryCode){
countryCode = PhoneNumberUtil.normalizeDigitsOnly(countryCode);
return mCountryByCode.get(countryCode);
}
public Country getCountryByName(String countryName){
return mCountryByName.get(countryName);
}
public Country getCountryByIsoCode(String ISO_code){
ISO_code = ISO_code.toUpperCase();
for (Country country:mCountries){
String [] strArr = country.ISO_code.split("/| ");
for (String s:strArr){
if (ISO_code.equals(s))
return country;
}
}
return null;
}
public String[] getCountryNamesList(){
String[] res = new String [mCountries.size()];
int i=0;
for (Country c:mCountries){
res[i] = c.Name;
i++;
}
return res;
}
public void readCountryCodesFromExcelWorkbook()
{
Context context = GlobalData.getInstance().getApp();
Workbook mWorkbook;
InputStream myRawResource = context.getResources().openRawResource(R.raw.countrycode_org);
if (myRawResource == null)
Toast.makeText(context,"XML file not found",Toast.LENGTH_LONG).show();
else
try {
WorkbookSettings ws = new WorkbookSettings();
ws.setEncoding("Cp1252");
mWorkbook = Workbook.getWorkbook(myRawResource);
//ArrayList<String[]> currentSheet = new ArrayList<String[]>();
Sheet sheet = mWorkbook.getSheet(0);
int rowsNum = sheet.getRows();
for (int rowNum = 1; rowNum < rowsNum; rowNum++) {
//Log.d("RowNum", ""+rowNum);
int colsNum = sheet.getColumns();
String[] strArr = new String[colsNum];
boolean rowIsFull = true;
for (int colNum = 0; colNum < colsNum; colNum++) {
strArr[colNum] = sheet.getCell(colNum, rowNum).getContents();
if (strArr[colNum].length() == 0)
rowIsFull = false;
}
if (rowIsFull)
addCountry(strArr[0],strArr[1],strArr[2]);
}
} catch (BiffException e) {
Toast.makeText(context,"Error Reading xml file: BiffException",Toast.LENGTH_LONG).show();
e.printStackTrace();
return ;
} catch (IOException e) {
Toast.makeText(context,"Error Reading xml file: IOException",Toast.LENGTH_LONG).show();
e.printStackTrace();
return ;
}
}
public Country[] getCountries(){
return mCountries.toArray(new Country[0]);
}
public class Country {
public String Name;
public String Code;
public String ISO_code;
}
}
Step-1
You can get country calling code as well as its ISO name in the following URL
http://en.wikipedia.org/wiki/List_of_country_calling_codes
or
http://www.unc.edu/~rowlett/units/codes/country.htm
Step-2 You can get page source of that file using java program. You will get file in HTMl format
Step-3 you can convert those HTML files into XML format using any of available parsers. see Open Source HTML Parsers in Java
Step-4 Form the phone number you can get the calling code. Example if the number is "1-319-491-6338" then calling code is 1
Step-5 Match this calling code against the calling code and country name list that you have got from XML parser. In this way you can get iso country

Categories

Resources