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")
Related
I want to comapare two textbox values words by words and check if the words are same or not. If its not same then it should tell me the percentage of matching words.
For example : I am a good boy(text box1)
Am a god boy (text box 2)
Then the result should be (3/5)*100 as 2 words are not matching that is I and good.
Please tell me how to do this.
here is a code as you want
public class Test {
public static void main(String[] args) {
String str1 = "I am a good boy";
String [] s_str1 = str1.split(" ");
String str2 = "Am a god boy";
String [] s_str2 = str2.split(" ");
int match = 0;
for(int i=0;i<s_str1.length;i++){
for(int j=0;j<s_str2.length;j++){
if(s_str1[i].equalsIgnoreCase(s_str2[j])){
match++;
}
}
}
int result = match*100/s_str1.length; //use length of string which is
your main str
System.out.println(result);
}
}
Try this:
int getCommonWords(String s1, String s2) {
Set<String> set1 = new HashSet<>(Arrays.asList(s1.split(" ")));
Set<String> set2 = new HashSet<>(Arrays.asList(s2.split(" ")));
set1.retainAll(set2);
return set1.size();
}
returns the number of common words between 2 strings. It is case-sensitive.
I know the title is confusing,
But I have a persistent problem when trying to get id key of existing string from strings.xml
like this
I have three values folders:
values , values-fr, values-ar;
and I have one string id:
R.id.center
when printed in screen, this id show:
in values
"Center"
in values-fr
"Centre"
in values-ar
"وسط"
My question is:
Is there a way to retrieve the int id by passing `"Center" or "Centre" or "وسط" as parameter
Someting like "وسط".getId, or ("Centre").getId
I know these methods doesn't exist :)`
Edit: Tested and working. Includes locale-support now.
public void listValues() {
Field[] fields = R.string.class.getFields();
String[] locales = Resources.getSystem().getAssets().getLocales();
for (int x = 0; x < locales.length; x++) {
System.out.println("checking for all ressources for the locale=" + locales[x]);
for (int i = 0; i < fields.length; i++) {
try {
System.out.println("name=" + fields[i].getName() + " value=" + getLocalizedResources(this, new Locale(locales[x])).getString(fields[i].getInt(fields[i].getName())));
} catch (IllegalAccessException ex) {
System.out.println(".. catch it if you want it");
} catch (RuntimeException rex) {
}
}
}
}
#NonNull
Resources getLocalizedResources(Context context, Locale desiredLocale) {
Configuration conf = context.getResources().getConfiguration();
conf = new Configuration(conf);
conf.setLocale(desiredLocale);
Context localizedContext = context.createConfigurationContext(conf);
return localizedContext.getResources();
}
I am an android noobie. What I am trying to do is to make this String an ArrayList. This is done. When i Print it On (with tv.setText) , the result is what i need but in this if i have right below i cannot find the "1".
The result i want to have is to store the text between the noumbers inside another ArrayList but to go there i have to be able to read the strings from the ArrayList.
public class MainActivity extends AppCompatActivity {
String text = "1Hello12People22Paul22Jackie21Anna12Fofo2";
TextView tv;
List<String> chars = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
PrinThemNow();
}
public void PrinThemNow(){
chars = Arrays.asList(text.split(""));
tv.setText(toString().valueOf(chars));
for(int i=0;i<chars.size();i++){
if(toString().valueOf(chars.get(i)) == " 1"){
Toast.makeText(this,"I found One",Toast.LENGTH_LONG).show();
//This if is not working while the TV's text shows " 1"
}
}
}
}
First, just a tip, from string to char[] you can use
char[] chars = myString.toCharArray();
because it has no sense to save a char array as a string ArrayList
but now the problem. you have your string and you wanna print the text between the numbers.
It's not really clear what is your goal but lets try.
I will suppose you used the char[] because it's 10 times better and easier
case 1) you wanna print text betweens "1"s
//lets loop the chars
bool firstOneFound = false;
int firstOccurrence = -1;
int secondOccurrence = -1;
int i = 0;
for(char c : chars){
//is it equals to 1?
if(c.equals('1')){
//check if we are already after the first 1
if(firstOneFound){
//if yes, we found the final one
secondOccurrence = i;
break;
}
else{
//this is the first occurrence
firstOccurrence = i;
firstOneFound = true;
}
}
i++;
}
if(firstOccurrence != -1 && secondOccurrence != -1){
String myFinalString = myString.subString(firstOccurrence, secondOccurrence);
}
case 2) you wanna print all text except numbers (maybe with a space instead)
for(char c : chars){
//check if it's a number
if(c >= '0' && c <= '9'){
//replace the number with anything else
c = ' '; //if you wanna have it as a space
}
}
//print the final string
String myFinalString = new String(chars);
NOTE:
You can also use ArrayList of string, just replace ' with "
hope it helps
I had a problem when I type the text I do not want the keyboard changes automatically, but after a space keyboard changes to the original state.
For example, I want to dial numbers that I move into this state the keyboard: But when I need to enter the number followed by a space, the keyboard itself is changed automatically:And it is necessary that the user himself can change the state of the keyboard, if it is necessary to enter characters. I use a mask on the text of Edit Text. With the help of this library set mask: MaskFormatter. an example of a mask: private static final String MASK = "99 AA 999999";
private EditText mInputCertificate;
#Override
public void setViews(View rootView, Bundle savedInstanceState) {
// Some code
mInputCertificate = (EditText) rootView.findViewById(R.id.input_car_certificate);
MaskFormatter maskFormatter = new MaskFormatter(MASK, mInputCertificate);
mInputCertificate.addTextChangedListener(maskFormatter);
}
There are ways to solve this problem?
I made my custom TextWatcher for EditText:
private String getString (String s) {
String newValue = s.replaceAll("\\s", "");
/*if (newValue.length() < 2 || newValue.length() >= 4) {
mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
} else {
mEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}*/
StringBuilder builder = new StringBuilder();
for (int i =0; i < newValue.length(); i++) {
if (i == 2 || i == 4) {
builder.append(' ');
builder.append(newValue.charAt(i));
} else {
builder.append(newValue.charAt(i));
}
}
return builder.toString();
}
#Override
public void afterTextChanged(Editable s) {
Log.d("EDITTEXT", "getEditable " + s);
String text = getString(s.toString());
mEditText.removeTextChangedListener(this);
mEditText.getText().clear();
mEditText.append(text.toUpperCase());
mEditText.addTextChangedListener(this);
mEditText.setSelection(mEditText.length());
}
This work for me. And I used .append(SomeText) instead .setText(SomeText).
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.