How to compare String from edittext not less than 10 in android? - android

I have an edit text in which user enters an amount and I want to compare that amount not less than 10, if found less than 10 then I want to show toast message. How can I do that?
m_szAmount = m_InputAmount.getText().toString().trim();
if (m_szAmount.equals(10)) {
m_InputAmount.setError("Please enter the amount between Rs. 10 and Rs. 1100");
} else {
confirmationDialog();
}

Try the below code:
m_szAmount = m_InputAmount.getText().toString().trim();
if (Integer.valueOf(m_szAmount) <= 10){
m_InputAmount.setError("Please enter the amount between Rs. 10 and Rs. 1100");
} else {
confirmationDialog();
}

try this:
m_szAmount = m_InputAmount.getText().toString().trim();
try
{
if (Integer.parseInt(m_szAmount)>10) {
m_InputAmount.setError("Please enter the amount between Rs. 10 and Rs. 1100");
} else {
confirmationDialog();
}
}
catch (NumberFormatException e) {
m_InputAmount.setError("Please enter Number");
}
if it is possible that user enter not number in your editText, it is important to use try catch while using Integer.parseInt() because it can raise exception if you will use it for not number string's.

try this :
String m_szAmount = m_InputAmount.getText().toString();
if(m_szAmount.replace(" ","").length() > 0) {
int inputAmount = Integer.valueOf(m_szAmount);
if (inputAmount >= 10 ){
m_InputAmount.setError("Please enter the amount between Rs. 10 and Rs. 1100");
m_InputAmount.requestFocus();
}else{
confirmationDialog();
}
}

try this:
m_szAmount = Integer.parseInt(m_InputAmount.getText().toString());
if( m_szAmount <= 10)
{
//show yout Toast
}
else
{
//do your work
}

TextWatcher textWatcher = 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) {
if(String.valueOf(s.length()) <= 10){
Toast.makeText(getContext(), "your text",Toast.LENGTH_LONG).show();
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
edit_explain.addTextChangedListener(textWatcher);

Related

SubString selection in EditText Android

Is there a way to capture text once # pressed until spacebar is pressed in EditText? Thanks in advance for your help.
First attach addTextChangedListener to your edittext and call a method which will match a particular condition like below:
EditText editText = (EditText)findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// 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 onTextChanged(CharSequence s, int start, int before, int count) {
try {
String capturedString = getText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
});
The above code will try to populate capturedString everytime a new character is added to the edittext field.
Now write another function getText() like below:
public String getText(String s) {
String startChar = "#";
String endChar = " ";
String output = getStringBetweenTwoChars(s, startChar, endChar);
System.out.println(output);
}
This method will match the provided string for # and space. If found, it will return the captured string if not found, it will throw an error (This error will be captured in catch block of the above code)
Now finally, write the below function which will intake a character sequence and two charecters and match the charecter sequence with the provided charecters and return the string between them:
public String getStringBetweenTwoChars(String input, String startChar, String endChar) {
try {
int start = input.indexOf(startChar);
if (start != -1) {
int end = input.indexOf(endChar, start + startChar.length());
if (end != -1) {
return input.substring(start + startChar.length(), end);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return input;
}
Hope this helps :)

Application get freeze whete set double value to edit text using typewriter for 2 edit text

I am developeing app where i want to change the currency value from one to another, Like i have 2 edittext. one for USD Currency to enter and other for EURO currency to enter.
Now i want to enter value in 1 edittext and the calculated value should display in other and same for the other edit text box.
TextWatcher inputTextWatcher = new TextWatcher()
{
public void afterTextChanged(Editable s)
{
try {
Start_Calculate(""+s.toString());
}
catch (NumberFormatException nfe)
{ //or whatever exception you get
}
//do some handling if you need to
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
};
amountET.addTextChangedListener(inputTextWatcher);
TextWatcher inputTextWatcher1 = new TextWatcher() {
public void afterTextChanged(Editable s)
{
try {
Start_Calculate2(""+s.toString());
}
catch (NumberFormatException nfe)
{ //or whatever exception you get
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
amount2ET.addTextChangedListener(inputTextWatcher1);
FUNCTION ARE HERE:
public void Start_Calculate(String val)
{
String user_input_value="00.00";
try
{
// user_input_value=""+amountET.getText().toString();
user_input_value=""+val;
}
catch(NumberFormatException e)
{
user_input_value="00.00";
}
//*/
if(!user_input_value.equalsIgnoreCase(""))
{
if(user_input_value.length()<11)
{
try
{
user_amount=Double.parseDouble(""+user_input_value);
}
catch(NumberFormatException e)
{
user_amount=00.000;
}
if(user_amount>0)
{
user_amount=user_amount*1.0000001;
total_amount_to_send=((user_amount*to_amount_val)/from_amount_val);
// total_amount_to_send= total_amount_to_send+00.0000;
//String total=new DecimalFormat("##.##").format(total_amount_to_send);
// totalTV.setText(user_amount+" "+fromTV.getText().toString()+" = "+ total+" ("+toTV.getText().toString()+")");
// totalTV.setText(user_amount+" = "+ total);
// String finalVal= df.format(target_currency_val);
//total_calTV.setText("( "+user_amount+" × "+df.format(to_amount_val) +" = "+ total+" )");
String total="00.00";
DecimalFormat df = new DecimalFormat("#.####");
total=""+df.format(total_amount_to_send);
try
{
amount2ET.setText(""+total);//_amount_to_send+"");
}
catch(Exception e)
{
Log.e("Error in Calculate1: ",""+e.getMessage());
}
//showtoast(""+total);//_amount_to_send);
//usdTV.setText(""+user_amount+" ("+fromTV.getText().toString()+")");
//pkrTV.setText(""+ total+" ("+toTV.getText().toString()+")");
}
else
{
}
}
else
{
}
}
}
public void Start_Calculate2(String val)
{
//String user_input_value="0";
//String user_input_value=""+val;
String user_input_value="0";
try
{
//user_input_value=""+amount2ET.getText().toString();
user_input_value=val;
}
catch(NumberFormatException e)
{
user_input_value="00.00";
}
//*/
if(!user_input_value.equalsIgnoreCase(""))
{
if(user_input_value.length()<11)
{
try
{
user_amount=Double.parseDouble(""+user_input_value);
}
catch(NumberFormatException e)
{
user_amount=00.00;
}
if(user_amount>0)
{
user_amount=user_amount*1.0000001;
total_amount_to_send=((user_amount*from_amount_val)/to_amount_val);
// total_amount_to_send= total_amount_to_send+00.0000;
//String total=new DecimalFormat("##.##").format(total_amount_to_send);
// totalTV.setText(user_amount+" "+toTV.getText().toString()+" = "+ total+" ("+fromTV.getText().toString()+")");
// totalTV.setText(user_amount+" = "+ total);
//DecimalFormat df = new DecimalFormat("#.##");
// String finalVal= df.format(target_currency_val);
//total_calTV.setText("( "+user_amount+" × "+df.format(to_amount_val) +" = "+ total+" )");
String total=new DecimalFormat("##.##").format(total_amount_to_send);
try
{
amountET.setText(""+total);//_amount_to_send);
}
catch(Exception e)
{
Log.e("Error in Calculate-2: ",""+e.getMessage());
}
//showtoast(""+total);//_amount_to_send);
//usdTV.setText(""+user_amount+" ("+fromTV.getText().toString()+")");
//pkrTV.setText(""+ total+" ("+toTV.getText().toString()+")");
}
else
{
//totalTV.setText("");
//total_calTV.setText("");
}
}
else
{
//totalTV.setText("");
//total_calTV.setText("");
}
}
}
It is because you get infinite loop.
amount2ET.setText will toggle another "afterTextChanged" let you repeat and repeat call of Start_Calculate.
You should remove the listener before set the text
amountET.removeTextChangedListener(inputTextWatcher)
try
{
amountET.setText(""+total);//_amount_to_send);
}
catch(Exception e)
{
Log.e("Error in Calculate-2: ",""+e.getMessage());
}
amountET.addTextChangedListener(inputTextWatcher);
Or you can set a global flag true when updating so you can dismiss another Start_Calculate:
boolean updating = false;
public void afterTextChanged(Editable s)
{
try {
if (!updating)
Start_Calculate(""+s.toString());
}
catch (NumberFormatException nfe)
{ //or whatever exception you get
}
//do some handling if you need to
}
Inside Start_Calculate:
updating = true;
try
{
amountET.setText(""+total);//_amount_to_send);
}
catch(Exception e)
{
Log.e("Error in Calculate-2: ",""+e.getMessage());
}
updating = false;

how give input in Edittext removing one character from hint at a time

**> I have a Edit Text with hint 0.00
Now i want to input text
If i press 5 it should appear 0.05
next if i press 4 it should come like 0.54**
this is the correct answer for my requirement
public static void decimalFormat(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
String before = "";
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
before = s.toString();
}
#Override
public void afterTextChanged(Editable s) {
if (!before.equalsIgnoreCase(s.toString())
&& !TextUtils.isEmpty(s.toString().trim())) {
before = s.toString();
String tvStr = s.toString();
if (tvStr.contains("-") || tvStr.equals(".")) {
editText.setText("");
}
if (!tvStr.equals("") && !tvStr.equals(".")) {
String cleanString = getFormatedNumber(tvStr, 2);
editText.setText(cleanString);
try {
editText.setSelection(cleanString.length());
return;
} catch (IndexOutOfBoundsException e) {
editText.setSelection(cleanString.length() - 1);
return;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
public static String getFormatedNumber(String text, int decimalPoint) {
String cleanString = text.replaceAll("[,.|\\s]", "");
if (TextUtils.isEmpty(cleanString)) {
return "0.00";
}
NumberFormat formatter = new DecimalFormat("#,##0.00");
double number = Double.parseDouble(cleanString) / (long) Math.pow(10.0, decimalPoint);
return formatter.format(number).toString();
}

How to validate date in dd/mm/yyyy format in editext in android?

I have two edittexts. I want to validate date entered in first edittext when I switch to next edittext... Is it possible?
I want to validate in dd/mm/yyyy format strictly..
please help me..
i searched and tried also but not get such a solution..
Step 1
youredittextname.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) {
// TODO Auto-generated method stub
Is_Valid_date(name); // pass your EditText Obj here.
}
});
Step 2
Write a function.
public void Is_Valid_date(EditText edt) throws NumberFormatException {
if (edt.getText().toString().length() <= 0) {
edt.setError("Accept number Only.");
valid_name = null;
} else if (check your date format using simpledate format) {
edt.setError("Accept Alphabets Only.");
valid_name = null;
} else {
valid_name = edt.getText().toString();
}
}
If you need to know Validate of the date.
Please visit this link.
http://www.mkyong.com/regular-expressions/how-to-validate-date-with-regular-expression/
Thank you.
private static final String DATE_PATTERN="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
private Pattern pattern= Pattern.compile(DATE_PATTERN);
public boolean isValidDate(final String date) {
Matcher matcher = pattern.matcher(date);
if (matcher.matches()) {
matcher.reset();
if (matcher.find()) {
String day = matcher.group(1);
String month = matcher.group(2);
int year = Integer.parseInt(matcher.group(3));
if (date.equals("31") && (month.equals("4")
|| month.equals("6")
|| month.equals("9")
|| month.equals("11")
|| month.equals("04")
|| month.equals("06")
|| month.equals("09"))) {
return false;
} else if (month.equals("2") || month.equals("02")) {
if (year % 4 == 0) {
if (day.equals("30") || day.equals("31")) {
return false;
} else {
return true;
}
} else {
if (day.equals("29") || day.equals("30") || day.equals("31")) {
return false;
} else {
return true;
}
}
} else {
return true;
}
} else {
return false;
}
} else {
return false;
}
}
Use interface TextWatcher in Android. You have to override its methods:
In onTextChanged() limit the length of text
In afterTextChanged() use some good regular expression for date validation. It will be available from Google.
SimpleDateFormat can be of your help. You can look for tutorials or else visit here

TextWatcher for multiple EditText

I want to be able to calculate something depending on the input in 2 of 3 EditText. For Example: I make an input in ET 1 and 2 -> i get a calculation in ET 3. ET 1 and 3 -> calculation in ET 2... and so on.
I get it to work with 2 EditText but with 3 I get an StackOverFlowError.
private class GenericTextWatcher implements TextWatcher {
private View view;
private GenericTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1,
int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1,
int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.liter_input:
try {
if (amount_widget.getText().toString().equals(" ") == false
|| literPrice_widget.getText().toString()
.equals(" ") == false
|| price_widget.getText().toString().equals(" ") == false) {
double editTextCalc = Double.parseDouble(amount_widget
.getText().toString())
* Double.parseDouble(literPrice_widget
.getText().toString());
editTextCalc = Math.round(editTextCalc * 100) / 100.0;
price_widget.setText(String.valueOf(decimalFormat
.format(editTextCalc)));
}
} catch (Exception e) {
// TODO: handle exception
}
break;
case R.id.literprice_input:
try {
if (amount_widget.getText().toString().equals(" ") == false
|| literPrice_widget.getText().toString()
.equals(" ") == false
|| price_widget.getText().toString().equals(" ") == false) {
double editTextCalc = Double.parseDouble(amount_widget
.getText().toString())
* Double.parseDouble(literPrice_widget
.getText().toString());
editTextCalc = Math.round(editTextCalc * 100) / 100.0;
price_widget.setText(String.valueOf(decimalFormat
.format(editTextCalc)));
}
} catch (Exception e) {
// TODO: handle exception
}
break;
case R.id.price_input:
try {
if (amount_widget.getText().toString().equals(" ") == false
|| literPrice_widget.getText().toString()
.equals(" ") == false
|| price_widget.getText().toString().equals(" ") == false) {
double editTextCalc = Double.parseDouble(amount_widget
.getText().toString())
/ Double.parseDouble(price_widget.getText()
.toString());
editTextCalc = Math.round(editTextCalc * 100) / 100.0;
literPrice_widget.setText(String.valueOf(decimalFormat
.format(editTextCalc)));
}
} catch (Exception e) {
// TODO: handle exception
}
break;
}
}
}
OK i just started to review my code again. Why hasn't anyone found an answer? It's really not that hard.
So i just just surrounded the if-statements in every try block with another if-statement which looks like this:
if(edittext.isFocused()){
try-catch block
}
And now everything works just fine. There is no StackOverflowException anymore because the textwatcher only starts it's work where the edittext is focused. The text changes do not trigger an infinit loop anymore.
You should check if change in an EditText happened because of changes made in other EditText. Create a boolean field in the class and initialize it with false:
private boolean mIsChanging = false;
In afterTextChanged() check if this field is false or exit otherwise:
public void afterTextChanged(Editable editable) {
if (mIsChanging) {
return;
}
mIsChanging = true;
// Then do what you did previously...
mIsChanging = false;
}
With Editable is possible, you need to use hashCodeFunction
#Override
public void afterTextChanged(Editable s) {
if (editText.getText().hashCode() == s.hashCode()) {
// some
}
}

Categories

Resources