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);
}
Related
Driving myself crazy over the simplest thing. I have a JSON file called config.txt. The file is shown below.
{
"UsePipesInGuestData": true
}
All I want to do is get a 2 dimensional array such that:
Array[0] = UsePipesInGuestData and
Array[1] = true
I have been trying for 4 hours with various attempts, my most recent is shown below:
private void getConfig(){
//Function to read the config information from config.txt
FileInputStream is;
BufferedReader reader;
try {
final File configFile = new File(Environment.getExternalStorageDirectory().getPath() + "/guestlink/config.txt");
if (configFile.exists()) {
is = new FileInputStream(configFile);
reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
if(line!= null) {
line = line.replace("\"", ""); //Strip out Quotes
line = line.replace(" ", ""); //Strip out Spaces
if ((!line.equals("{")) || (!line.equals("}"))) {
} else {
String[] configValue = line.split(":");
switch (configValue[0]) {
case "UsePipesInGuestData":
if (configValue[1].equals("true")) {
sharedPreferences.edit().putString("UsePipes", "true").apply();
} else {
sharedPreferences.edit().putString("UsePipes", "false").apply();
}
break;
}
}
}
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I cannot seem to ignore the lines with the { and } in them.
Clearly there MUST be an easier way. JAVA just seems to take an extremely large amount of code to do the simplest thing. Any help is greatly appreciated.
I believe your condition is incorrect. You try to read the file in the else of the condition (!line.equals("{")) || (!line.equals("}")). Simplifying, your code will run when the following happens:
!(!{ || !}) => { && } (applying De Morgan's law)
This means you will only run your code when the line is "{" AND it is "}" which is a contradiction. Try using simple conditions, like (!line.equals("{")) && (!line.equals("}")) (this is when you want to execute your code).
Additionally, you may be getting end of line characters (\n) in your string, which will make your condition fail ("{\n" != "{"). I suggest you debug and see the actual values you're getting in those lines.
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'd like an inputType in the edit text that i can input fractional number like this: 2/4 (i want print the "/").
The program is about calculating things and i need to type fractional insted of decimal. Thanks. Sorry my bad english.
I think the best way would be to use a string for your input text, then to parse the string to figure out what kind of things the user entered.
When the user has finished their input, you can check the string with something like this:
public float testInputString(String testString) {
boolean goodInput = true;
float result = 0;
if (testString.contains("/")) {
//possible division
String pieces[] = testString.split("/");
if (pieces.length != 2) {
goodInput = false;
} else {
try {
float numerator = Float.parseFloat(pieces[0]);
float denominator = Float.parseFloat(pieces[1]);
result = numerator/denominator;
} catch (Exception e) {
goodInput = false;
}
}
} else if (testString.contains(".")) {
try {
result = Float.parseFloat(testString);
} catch (Exception e) {
goodInput = false;
}
}
//TODO something here if bad input, maybe an alert or something
return result;
}
Also, you can check while they are typing for valid input if you use a keylistener like this. You could modify that to allow only numbers . and /.
put this property in xml node of Edittext and use Double notation instead of "/"
android:digits="1234567890.-"
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 doing a program where users can use regular expressions to search in text, and I want to let the matching text to be selected. So I use this code:
public void onClick(View v) {
try {
switch (v.getId()) {
case R.id.btn_search:
Matcher m = Pattern.compile(reg.getText().toString()).matcher(txt.getText());
int start = txt.getSelectionStart();
if (start != txt.getSelectionEnd()) {
start++;
}
if (start < 0 || start >= txt.length()) {
start = 0;
}
while (true) {
try {
m.find(start);
txt.setSelection(m.start(), m.end());
txt.requestFocus();
break;
} catch (IllegalStateException ex) {
if (start == 0) {
err_notfound.show();
break;
}
start = 0;
}
}
break;
}
} catch (PatternSyntaxException ex) {
err_syntax.show();
} catch (Throwable ex) {
showException("onClick", ex);
}
}
However the code is not acting as expected. When I put the cursor manually to a position, and then press the search button, sometimes the program will set the cursor to m.start() but do not expand the selection to m.end(). I have tested the program, and m.start() and m.end() are of different values.
If anyone know what causes the problem, please tell me. I'll appreciate it.
Edit: Thank you for helping! I find an answer to the question. It has something to do with the pin which is used to move the cursor and select text (I don't know what it's called...). If it is shown in the textfield, and setSelection() is called, the EditText will not show the selection correctly. However, if you then use getSelectionStart() and getSelectionEnd(), you'll find they are exactly the same value of m.getStart() and m.getEnd(). This could be a bug. So my solution is to call clearFocus() first. The modified code is like this:
txt.clearFocus();
while (true) {
try {
m.find(start);
txt.setSelection(m.start(), m.end());
txt.requestFocus();
break;
} catch (IllegalStateException ex) {
if (start == 0) {
err_notfound.show();
break;
}
start = 0;
}
}
And it works.
I tested your code and put in one modiication.
Matcher m = Pattern.compile("1*", Pattern.CASE_INSENSITIVE).matcher(txt.getText());
I then made sure that my EditText had only 1's and it highlighted the entire thing.
You many need to confirm that your Regular Expressions are written correctly. You could see more on regualr expressions here(same site I just used).