3

I've got an EditText in my app, in which I don't want users to enter numbers with more than 3 decimal places. This is because in the SQL server database that is going to store that data I send from the phone has this data type :

numeric(15, 3)

Do you have any idea how I can do that?

I've already set these values, but they would only help me partially:

android:maxLength="15"
android:lines="1"
android:inputType="numberDecimal"

Edit

This is what I tried:

            mQuantityEditText.addTextChangedListener(new TextWatcher(){
        @Override
        public void afterTextChanged(Editable s) {
            String str = mQuantityEditText.getText().toString();
            DecimalFormat format=(DecimalFormat) DecimalFormat.getInstance();
            DecimalFormatSymbols symbols=format.getDecimalFormatSymbols();
            char sep=symbols.getDecimalSeparator();


            int indexOFdec =  str.indexOf(sep);         

            if(indexOFdec >=0) {
               if(str.substring(indexOFdec,str.length()-1).length() >3)
               {
                    s.replace(0, s.length(),str.substring(0, str.length()-1));                    
               }
            }
         }
        @Override
         public void beforeTextChanged(CharSequence s, int start, int count, int after) {

         }
        @Override
         public void onTextChanged(CharSequence s, int start, int before, int count) {                      


         }      
     });

It worked because it only allows 3 decimal places, but I'm still not sure how to control the max number of digits to fit in the numeric(15,3)

Thanks in advance.

Axel
  • 1,674
  • 4
  • 26
  • 38

2 Answers2

0

For the limited number of character, you can add a Android API filter :

InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(8);
editEntryView.setFilters(FilterArray);

For the numeric editText, there is also a obscur solution :

DigitsKeyListener MyDigitKeyListener = new DigitsKeyListener(true, true); 
editEntryView.setKeyListener( MyDigitKeyListener );
0
public class RestrictDecimal implements InputFilter {

Pattern mPattern;

public RestrictDecimal(int beforePoint,int afterPoint) {
    mPattern=Pattern.compile("[0-9]{0," + (beforePoint-1) + "}+((\\.[0-9]{0," + (afterPoint-1) + "})?)||(\\.)?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

        Matcher matcher=mPattern.mat`enter code here`cher(dest);       
        if(!matcher.matches())
            return "";
        return null;
    }

}

// Set for edit Text
editEntryView.setFilters(new InputFilter[] {new RestrictDecimal(15,3)});
Rohitashv jain
  • 244
  • 1
  • 15