Unexpected behavior when using EditText.setSelection() - android

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).

Related

How to fix encoding problem with Czech chars, while using BluetoothManager for printing?

I've got the old project in Java and for sure I met there with some small problem.
here is the code:
public boolean printerPrint(List<String> list) {
if (btMan != null) {
try {
// Select character code table (ESC t n) - n = 16(0x10)
btMan.getOutputStream().write(0x1B);
btMan.getOutputStream().write(0x74);
btMan.getOutputStream().write(0x10);
for (String s : list) {
byte[] byteLine = (s).getBytes(ISO_8859_1);
String line = Util.byte2HexStr(byteLine) + " 0A";
btMan.SendData(line);
}
btMan.SendData("0A 0A 0A");
} catch (Exception e) {
Timber.e(e, "printing stop failed");
}
}
return true;
}
Here is the screenshot from the app, this bill should be the same after print.
Here is the bill after print:
Some of the letters are not printed (š, ě, č, ř, ž), but they have been replaced by "?".
I tried to use ISO8859-2(the same problem as in ISO-8859-1, but instead of replacement by "?", they have been replaced by some letters which aren't correct), UTF8/UTF-8(especially with this it doesn't work at all).
If someone ever met with that, any advice is good.

Can editText.getText().toString().trim().length() ever generate NullPointerException?

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

Android: Getting into right condition using fileinputstream

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")

android exception for validating file exist not working

I've been working with Eclipse ADT for about 2 months. In that time, I have a small utility that allows me to select an IP Address and Port, and then send a file to that combo. The utility works as intended, but when I type in the wrong file name, the application hangs.
#Override
public void run() {
if (data != null) {
this.send(data);
} else if (this.file != null) {
if (file.exists()) {
this.send(file);
} else {
transferError = new FileNotFoundException("The specified file could not be found");
}
}
}
I've even tried to do the following in hopes that one or the other would throw, but I am unsuccessful in both.
public void run() {
if (data != null) {
this.send(data);
} else if (this.file != null) {
if (file.exists()) {
this.send(file);
} else {
transferError = new FileNotFoundException("The specified file could not be found");
}
}try {
throw new Exception("blah blah blah");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I've jockeyed around the exception, I've added the one above, I've tried placing it in different places, and all unsuccessful. Again, I'm exceptionally new to this, and got here from basically mincing various tcp client codes. Aside of creating a way to throw the exception correctly, please help me understand why the first one isn't working and why the one you suggest is.
in your else block you aren't throwin the transferError you create.
throw transferError;
However you probably won't be able to do that because FileNotFoundException is a checked exception and the run() method doesn't declare any thrown exceptions. You probably need to find a different way to present the error to the user, like with a Toast or something.
Your second block doesn't work because you are catching the exception you throw.

Vibrator.vibrate() throws ArrayIndexOutOfBoundsException

I use the following snippet to vibrate the phone in a specific pattern, but it throws and ArrayIndexOutOfBoundsException.
vibrator.vibrate(new long[] { selectedDuration, CONSTANT_DELAY }, REPEAT);
But
vibrator.vibrate(VIBRATE_DURATION);
works fine. Any pointers?
The docs say:
If you want to repeat, pass the index into the pattern at which to start the repeat.
Means REPEAT is only allowed to be 0 or 1 in your case.
This is the implementation:
public void vibrate(long[] pattern, int repeat)
{
// catch this here because the server will do nothing. pattern may
// not be null, let that be checked, because the server will drop it
// anyway
if (repeat < pattern.length) {
try {
mService.vibratePattern(pattern, repeat, mToken);
} catch (RemoteException e) {
}
} else {
throw new ArrayIndexOutOfBoundsException();
}
}

Categories

Resources