In my app I need the global system locale and I'm currently taking it as follows
public static Locale getSystemLocale() {
Locale locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
locale = Resources.getSystem().getConfiguration().getLocales().get(0);
} catch (Exception e) {
e.printStackTrace();
locale = Locale.getDefault();
}
} else {
locale = Resources.getSystem().getConfiguration().locale;
}
return locale;
}
But I am wondering is this try catch block is really necessary, can getLocales() either return null or return an empty array ? Thanks
The answer is NO, you don't need to surround that code with a try catch block.
Because it doesn't throw exceptions (in the normal scenarios). Fortunately, Android studio warns you to surround the code that could potentially throw exceptions in the first place so you don't have to worry. :)
For example if you are trying to convert a string to number you are only expecting numbers to be present in the string if the string contains anything else except numbers the process of converting string to number can throw and exception. So you should surround such code with try catch block.
Related
I have many EditText in my app and I have used below code to check whether EditText is empty or not.
if (etEditText.getText().toString().trim().length() > 0)
EditText is initialized properly but I have not added null check since I read that getText().toString() never returns null. Can above code ever generated NullPointerException assuming that EditText is initialized properly? I want to be safe in every situation.
Proper way to null check as follows.
if (etEditText != null) {
String str = etEditText.getText().toString();
if (!TextUtils.isEmpty(str) && (str = str.trim()).length() > 0) {
// str will be trimmed text
// Do your work here
}
}
This is not a recommended way to check for a null string. Try this instead:
String text = etEditText.getText().toString();
if(!text.isEmpty()) {
....
}
And the remaining part where you are asking about NullPointerException,
EditText.getString() rarely generates that but it sometimes does, so it's better to enclose the code with a try and catch block like so:
try {
String text = etEditText.getText().toString();
if(!text.isEmpty()) {
...
}
} catch(NullPointerException e) {
e.printStackTrace();
}
String value = textInputEditText.getText().toString().trim();
if (value.isEmpty()) {
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
} else {
textInputLayout.setErrorEnabled(false);
}
Basically I need to create extract string resources and sometimes for locale there is no string resource available. Is there any way to get string or null if it is not found? I do not want to do try-catch every time it is missing
try {
valuesForLocale.put(key, res.getString(key.id));
} catch (Resources.NotFoundException e) {
//Ignore
}
Is there anything like getStringOrNull()?
You can use getIdentifier method. The code without try-catch will look similar to:
int stringId = context.getResources().getIdentifier("my_resource_name", "string", mContext.getPackageName());
String text = (stringId != 0) ? context.getString(stringId) : "";
I'm facing a different problem, see below is the code for my app that can read stored file and have to check condition according to that.
My inputs are "ON" and "OFF"
String val="";
final ToggleButton start = (ToggleButton) findViewById(R.id.startup);
FileInputStream fileos;
try {
fileos = openFileInput("startup");
byte[] input = new byte[fileos.available()];
while(fileos.read(input) != -1){
val += new String(input);
}
if(val.toString() == "ON"){
start.setChecked(true);
}else if(val.toString() == "OFF"){
start.setChecked(false);
}else{
start.setChecked(true);
}
fileos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The above code fetching the output correctly either "ON" or "OFF", But it Always going into else conditionelse
else{ start.setChecked(true); }
I'm stucked here, Please help me some one
android is based in java , in java you can't use "==" to compare two strings , you should replace
val.toString() == "ON"
to
"ON".equals(val.toString())
There are actually two big problems with this code. One is that you must use the equals() method to compare String objects, always -- the == operator is appropriate only in very limited cases.
The second one is more subtle, and won't break all the time. When you read data into input, although you're using a loop, the code will only work if all the data is read at once. This is because you're creating a String out of the entire array, even if the entire array doesn't contain valid data. The correct loop would look like this:
int count;
while((count = fileos.read(input)) != -1){
val += new String(input, 0, count);
}
you have to compare the string using .equals()
if(val.equals("ON")){
start.setChecked(true);
}else if(val.equals("OFF")){
start.setChecked(false);
}else{
start.setChecked(true);
}
Use String.equals() to compare Strings. Do no use ==
val.toString().equals("ON")
I am receiving an exception when I try to get the field of a resource in an Android application. It seems like correct way of accessing a drawable id. Any suggestions what could be wrong?
04-09 22:45:59.816: W/System.err(5014): java.lang.NoSuchFieldException: lumiere
In my res/drawable folder I have "lumiere.jpg". From R.java:
public static final class drawable {
[...]
public static final int lumiere=0x7f02000a;
method call:
Class c = R.drawable.class;
field = c.getField(name);
i = new Integer(field.getInt(null));
I don't think this matters, being a static class method call, but just in case it does - the above code is in a plain Java class, not an Activity. Just thought I'd mention since access to resources seems restricted outside of Activities.
I believe you meant to use c.getDeclaredField(name). Also (and this might be the more "correct" way to do it), you can use the Resources object to get the ID when you have the name. See this question/answer.
I think you need to provide class's object when calling getInt method:
Integer i = null;
try {
Class c = R.drawable.class;
Field field = c.getField(name);
if(field != null){
i = new Integer(field.getInt(c)); //provide 'c' in getInt
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Read this post
Unfortunately, it appears that you in fact cannot use this to access resources contained in R.java file from a plain Java class. When I copied the code into a class that is an Activity, it did not throw an exception and returned a value.
I want to translate my text into device language.
So I tried below code
String InputString="My text";
String OutputString = null;
Language fromLanguage = Language.ENGLISH;
Language toLanguage = Language.valueOf(Locale.getDefault().getDisplayLanguage().toUpperCase());
try {
Translate.setHttpReferrer("http://android-er.blogspot.com/");
OutputString = Translate.execute(InputString,
fromLanguage, toLanguage);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
OutputString = InputString;
}
return OutputString;
If device language is English it executes well but i changed to any other language then it shows
java.lang.IllegalArgumentException: FRANÇAIS is not a constant in the enum type class com.google.api.translate.Language
not FRANCAIS if I select any language except English it shows IllegalArgumentException with selected language.
What have I done wrong, or is there another way to translate text into device language?
Read this document, it explains all you need to know: Android Localization