s.replace() not working in Android EditText in TextWatcher - android

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.

Related

Add dash/hyphen after 4 digits in edittext in android

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.

String encryption in editext

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.

How do I format a string into EditText in Android with "AAA-AAA-AAA" format

I need to get an input of 9 uppercase letters separated by dash like AAA-AAA-AAA and
this input has to be formatted while is entered.
Thanks in advance.
I have found the solution using a TextWatcher. I'm using
android:inputType="textCapCharacters|textNoSuggestions"
for the EditText input type in order to receive only uppercase letters.
txtCode = (EditText) findViewById(R.id.txtCode);
txtCode.addTextChangedListener( new TextWatcher() {
boolean isEdiging;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) {
if(isEdiging) return;
isEdiging = true;
// removing old dashes
StringBuilder sb = new StringBuilder();
sb.append(s.toString().replace("-", ""));
if (sb.length()> 3)
sb.insert(3, "-");
if (sb.length()> 7)
sb.insert(7, "-");
if(sb.length()> 11)
sb.delete(11, sb.length());
s.replace(0, s.length(), sb.toString());
isEdiging = false;
}
});
You can do this by text change listner
when text_size%3==0 insert "-" character

NumberFormatException in EditText

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.

Customize editext input in android

How can I customize input type of editext shown in the given figure.Basically my requirement is that edittext should show only the last 3 or 4 digits only initial 12 digit should be in password mode.
You need to add a TextWatcher onto the EditText:
int characterCount = 0;
int asteriskCount = 0;
CharSequence input = null;
input.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
characterCount = count;
//update input sequence based on changes.
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//update input sequence based on changes.
}
#Override
public void afterTextChanged(Editable s) {
if (asteriskCount != characterCount) {
//make the visible sequence here.
CharSequence seq = "";
for (int i = 0; i < (characterCount <= 12 ? characterCount : 12); i++) {
seq = seq + "*";
}
if (characterCount > 12) {
for (int i = 12; i < characterCount; i++) {
seq = seq + characterCount.charAt(i);
}
}
asteriskCount = characterCount;
input.setText(seq);
}
}
});
There is no built in feature like this. So you have to do it by yourself. You have to make change on the text when the text is changed. To do so .
If you create a custom editText by extending EditText then you can overwrite the onTextChanged method and hanlde the changes.
Or you can use a TextWatcher to hadle changes.
So when the text is changed set the data except last 3 digitst to *.
But remember that you have to use a String field to store original data in a field.
Below is the code snippet of my TextWatcher:
private boolean spaceDeleted;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
characterCount = start;
//update input sequence based on changes.
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// check if a space was deleted
CharSequence charDeleted = s.subSequence(start, start + count);
spaceDeleted = " ".equals(charDeleted.toString());
}
#Override
public void afterTextChanged(Editable s) {
if(s.length()>12){
return;
}
System.out.println("Character Count in afterTextChange->"+characterCount);
System.out.println("Editable Character->"+s);
ccNumber.removeTextChangedListener(this);
// record cursor position as setting the text in the textview
// places the cursor at the end
int cursorPosition = ccNumber.getSelectionStart();
String withSpaces = formatText(s);
ccNumber.setText(withSpaces);
// set the cursor at the last position + the spaces added since the
// space are always added before the cursor
ccNumber.setSelection(cursorPosition + (withSpaces.length() - s.length()));
// if a space was deleted also deleted just move the cursor
// before the space
if (spaceDeleted) {
ccNumber.setSelection(ccNumber.getSelectionStart() - 1);
spaceDeleted = false;
}
// enable text watcher
ccNumber.addTextChangedListener(this);
}
private String formatText(CharSequence s) {
// TODO Auto-generated method stub
StringBuilder formatted = new StringBuilder();
int count = 0;
/* if(s.length()<12){
formatted.append("*");
}else{
formatted.append(s.charAt(characterCount));
}*/
for (int i = 0; i < s.length(); ++i)
{
formatted.append("*");
/*if (Character.isDigit(s.charAt(i)))
{
if (count % 4 == 0 && count > 0)
formatted.append(" ");
formatted.append(s.charAt(i));
++count;
}*/
}
return formatted.toString();
}
});

Categories

Resources