I have a TextView that calculates two EditText. It works as long as a digit is in the EditText but as soon all numbers are deleted I get this error
java.lang.NumberFormatException: unable to parse '' as integer
I understand why I'm getting the error but I cant figure out how to fix it. I've googled and searched for answers on this site but they don't seem to work for my situation. I've tried to catch the NumberFormatException but I cant do it. Any help?
items = (EditText)findViewById(R.id.items);
itemcost = (EditText)findViewById(R.id.itemcost);
inventoryvalue = (TextView)findViewById(R.id.inventoryvalue);
TextWatcher textWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
calculateResult();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
};
items.addTextChangedListener(textWatcher);
itemcost.addTextChangedListener(textWatcher);
}
private void calculateResult() throws NumberFormatException {
String s1 = items.getText().toString();
String s2 = itemcost.getText().toString();
int value1 = Integer.parseInt(s1);
int value2 = Integer.parseInt(s2);
int result = value1 * value2; {
// Calculates the result
result = value1 * value2;
// Displays the calculated result
inventoryvalue.setText(String.valueOf(result));
}
Check if your String contains only number:
s1 = s1.trim();
if (s1.matches("[0-9]+") {
value1 = Integer.parseInt(s1);
}
in the calculateResult method put everythin in an if block:
if(items.getText().tostreing().length>0 && itemcost.getText().toString().length>0){
//your current method definition
}
Change your afterTextChanged method to:
public void afterTextChanged(Editable s) {
if (s.length > 0)
calculateResult();
}
In calculateResult() you do Integer.parseInt(s1); without checking if String s1 or s2 are empty?
Thus you cant convert an empty String to Int. Try checking if s1 or s2 are empty before trying to convert them to Integers and calculating with them...
You can use : .equals(String s) to check if Strings are equal to others.
Related
I have an EditText that converts user input, for example, 1000000 to 1,000,000. this is the code I use as a converter:
private TextWatcher onTextChangedListener(final EditText editText) {
return new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
editText.removeTextChangedListener(this);
try {
String originalString = s.toString();
Long longval;
if (originalString.contains(",")) {
originalString = originalString.replaceAll(",", "");
}
longval = Long.parseLong(originalString);
DecimalFormat formatter = new DecimalFormat("###,###,###");
String formattedString = formatter.format(longval);
//setting text after format to EditText
editText.setText(formattedString);
editText.setSelection(editText.getText().length());
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
editText.addTextChangedListener(this);
}
};
}
When I tried it on the emulator (both API 25 and 29), it behaves correctly, the EditText I type in the right format (1,000,000) but when I release the application, people are reporting that the format has become 1.000000 and then when the function around EditText is used, the app crashes, the store crash report says it's a NumberFormatException. What can possibly cause this and how do I work around it?
Turned out to be locale problem, that code I used there provide no locale setting which results in a different format if another device is using different locale. So I implement this code:
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
DecimalFormat formatter = new DecimalFormat("###,###,###", symbols);
And it works fine with a device with a different locale
I was implemented like after 4 digits hyphen display automatically like(2015-07) in edittext. my code works fine, but problem is while i delete before 4 digits value and again type it not working. addTextChangedListener not trigger when i edidtext retype like 2015-07 to 2014-07. But while i using "/" instead of "-" i can retype value. What is the problem?
mEdtProductionCode.addTextChangedListener(new TextWatcher() {
int prevL = 0;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
prevL = mEdtProductionCode.getText().toString().length();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
int length = s.length();
if ((prevL < length) && length == 4) {
String data = mEdtProductionCode.getText().toString();
mEdtProductionCode.setText(data + "-");
mEdtProductionCode.setSelection(length + 1);
}
}
});
You should just move your character checking to the character after the fifth character has been entered, and then chop down String to put the custom character in between:
#Override
public void afterTextChanged(Editable s) {
int length = s.length();
if ((prevL <= length) && length == 5) {
String data = mEditProductionCode.getText().toString();
String beginData = data.substring(0,4);
String endData = Character.toString(data.charAt(length-1));
mEditProductionCode.setText(beginData + "-" + endData);
mEditProductionCode.setSelection(length + 1);
}
}
You can also use data.charAt(length-1) != '-' to check if user manually made dash input, in which case you just ignore and do not make changes to TextEdit.
I have got an EditText in my Android app where you can type in some text. What I want to do is change only first character to another one (some kind of enciphering). Therefore I first have to read every single character.
How can I do that?
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.answer);
ed1=(EditText)findViewById(R.id.answer);
String s=ed1.getText().toString();
abc(s);
}
public void abc(String s){
//get your string
String str = s;
//turn it into an array of chars
char[] strChars = str .toCharArray();
//set array at position 1 to an x
strChars[1] = 'x';
str = String.valueOf(strChars);
ed1.setText(str);
}
Something like this would work:
//get your string
String str = "whatevertextyouwanthere";
//turn it into an array of chars
char[] strChars = str .toCharArray();
//set array at position 1 to an x
//Check to make sure the length is above -
if (str.length() != 0)
{
//Check that we have a value of some sorts in the char array
if (strChars[0] != ''
{
//replace the char at place 0 with X
strChars[0] = 'x';//this might need to be 1
}
}
//turn the array back into a string
str = String.valueOf(strChars);
Ideally you should have this within a function for ease of use and re-usability. It should return whatever the value of str is.
Post this in your onCreate:
ed1.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
abc(ed1.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
}
The above was just some code I wrote really quickly but should do what you need it to do. You need to have a listener watching for changes to the edit text.
i need to remove characters if i add any special symbols to the edit text while am entering data to it.for example i am type a word smwinæ æ is a special characters so if i add that chareter edit text should remove the æ and display only smwin by replacing æ .i used text change listener. check the code below
email.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// Abstract Method of TextWatcher Interface.
System.out.println("started after");
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
System.out.println("started");
// Abstract Method of TextWatcher Interface.
}
public void onTextChanged(CharSequence searchcontact, int start,
int before, int count) {
System.out.println("sssssssssss"+searchcontact);
String a=searchcontact.toString();
System.out.println("casted "+a);
String[] parts = a.split(" ");
String lastWord = parts[parts.length - 1];
System.out.println("------------------------------"+lastWord);
// String lastWord = a.substring(a.lastIndexOf(" ")+1);
// System.out.println("lastword"+lastWord);
if(a.equals("p"))
{
try {
email.getText().delete(email.getSelectionEnd() - 1, email.getSelectionStart());
} catch (Exception e) {
try {
email.getText().delete(email.length() - 1, email.length());
} catch (Exception myException) {
//textfield.getText().delete(textfield.length(), textfield.length() - 1);
}
}
// Method User For Sort Out THE Words
// in
// The SearchBar
}
}
});
here when text change i try to get the last word in the string but i failed to do this.used
String a=searchcontact.toString();
System.out.println("casted "+a);
String[] parts = a.split(" ");
String lastWord = parts[parts.length - 1];
to get the last word but it prints the entire string in the edittext how can i do this please help
You can add a TextWatcher to an EditText and get notified each time the text is notified. Using that, you can just parse the String to find the characters after a space, and update them to uppercase.
Here's a quick test I made which works pretty well (far from optimal, because each time you edit the Editable it calls the listener again...).
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
String string = s.toString();
int index = -1;
while (((index = string.indexOf(' ', index + 1)) != -1) && (index + 1 < string.length())) {
// Get character
char c = string.charAt(index + 1);
if (Character.isLowerCase(c)) {
// Replace in editable by uppercase version
s.replace(index+1, index + 2, Character.toString(c).toUpperCase());
}
}
}
});
To avoid being called to often, you could make all the changes in a char[] and only commit to the Editable if changes were made.
A simpler solution is probably to just use split(' ') on your String, replace all first letters in the String[] by the uppercase version (if needed), and commit only once to the Editable.
A simpler optimisation would be to add a boolean to your anonymous class, set it to try when you enter afterTextChanged, set it back to false when you exit it, and only process the string if the boolean is false.
I have an EditText in which the user should input a number including decimals and i want a thousand separator automatically added onto the input number
I tried a couple of other methods but some do not allow floating point numbers
so i came up with this code which works well only that the string input is not being edited in realtime to one with possible thousand separators and the errors seem to stem from the s.replace();
am2 = new TextWatcher(){
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
public void afterTextChanged(Editable s) {
if (s.toString().equals("")) {
amount.setText("");
value = 0;
}else{
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < amount2.getText().toString().length() ; i++) {
c = amount2.getText().toString().charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
value = Double.parseDouble(strBuff.toString());
reverse();
NumberFormat nf2 = NumberFormat.getInstance(Locale.ENGLISH);
((DecimalFormat)nf2).applyPattern("###,###.#######");
s.replace(0, s.length(), nf2.format(value));
}
}
};
I think you should use setText() of the edittext once the text is changed
do something like this
editext.setText(s); after you replace your string
simple s = s.replace(0, s.length(), nf2.format(value));
That is variable s need to be assigned.