Reputation: 173
How would I get that when Comma "," is entered in Edit text. Here what I am doing
newCategryET.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence returnedResult, int start,
int before, int count) {
String result = returnedResult.toString();
String result2 = result.substring(result.length() - 2,
result.length() - 1);
if (result2.equals(",")) {
addCategoryToLayout(result.substring(0, result.length() - 1));
newCategryET.setText("");
return;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
I want to add the text of my Edit text to a layout whenever Comma is pressed But I am getting array index out of bound exception.
Any Help
Here is my logcat error -
java.lang.StringIndexOutOfBoundsException: length=1; regionStart=-1; regionLength=1
Upvotes: 0
Views: 1694
Reputation: 1914
Try this way, hope this will work
@Override
public void onTextChanged(CharSequence returnedResult, int start,
int before, int count) {
if (count > 0) {
String s1 = "" + result.charAt(start);
if (s1.toString().equals(",")) {
addCategoryToLayout(result.substring(0, result.length() - 1));
newCategryET.setText("");
return;
}
}
}
Upvotes: 0
Reputation: 5030
@Override
public void onTextChanged(CharSequence returnedResult, int start, int before, int count)
{
String result = returnedResult.toString();
if(result.length() == 0) return;
//if(result.contains(",")) // another method
if(result.charAt(result.length() - 1).equals(",") // last character is ','
{
// comma is entered
addCategoryToLayout(result.substring(0, result.length() - 1));
newCategryET.setText("");
}
}
Upvotes: 0
Reputation: 7521
Consider the case when the very first character is entered (as q):
Trying to take this subtsring starting at position -1 causes your exception.
There are several easier solutions to this problem - such as checking String.contains(",") or String.IndexOf()
Upvotes: 2
Reputation: 2326
you can use the string's contains method to check that the string contains comma or not
String.contains(",")
and then you use string tokenizer to split the string whenever the comma appears
Upvotes: 2