TextWatcher for multiple EditText - android

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
}
}

Related

App crashes when "=" button is pressed when getText is empty - Android Studio

I have a calculator app that crashes when the equals button is pressed and there is nothing in the EditText that it getTexts from. I have looked at the other questions with similar situations, but those suggestions are not working. I am new to android and would like any help. I also have the issue if I have a "0" in my EditText.setText(), the "0" stays in front of the other numbers when they are pressed. Please let me know if you need more of the code to help.
Here is the Logcat info
09-08 07:58:32.915 13726-13726/com.ruthadeaton.bld3.calculator
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ruthadeaton.bld3.calculator, PID: 13726
java.lang.NumberFormatException: empty String
atsun.misc.FloatingDecimal.readJavaFormatString
(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.lang.Float.parseFloat(Float.java:451)
at com.ruthadeaton.bld3.calculator.MainActivity$26.onClick
(MainActivity.java :346)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run
(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Here is my code:
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueTwo=Float.parseFloat(edt1.getText() + "");
if (mAddition == true) {
edt1.setText(mValueOne + mValueTwo + "");
mAddition=false;
}
if (mSubtract == true) {
edt1.setText(mValueOne - mValueTwo + "");
mSubtract=false;
}
if (mMultiplication == true) {
edt1.setText(mValueOne * mValueTwo + "");
mMultiplication=false;
}
if (mDivision == true) {
edt1.setText(mValueOne / mValueTwo + "");
mDivision=false;
}
}
});
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edt1.setText(edt1.getText() + "0");
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne=Float.parseFloat(edt1.getText() + "");
mAddition=true;
edt1.setText(null);
}
});
buttonSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne=Float.parseFloat(edt1.getText() + "");
mSubtract=true;
edt1.setText(null);
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne=Float.parseFloat(edt1.getText() + "");
mMultiplication=true;
edt1.setText(null);
}
});
buttonDivision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne=Float.parseFloat(edt1.getText() + "");
mDivision=true;
edt1.setText(null);
}
});
I have a calculator app that crashes when the equals button is pressed
and there is nothing in the EditText that it getTexts from.
Because you do not validate the input from users is valid or not. Obviously empty string is not a number that why the app crashes with NumberFormatExecption.
I also have the issue if I have a "0" in my EditText.setText(), the
"0" stays in front of the other numbers when they are pressed.
You can use TextWatcher to update the text view based on input from users.
I will guide you step by step how to fix those issues
First, define a method which validates input from users is a valid number or not.
private boolean isValidNumber(String numberInString) {
try {
Float.parseFloat(numberInString);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Second, each time users press on a arithmetic operator (+, -, *, /) or equal (=) the app will get value from the edt1. Then write a method to do that to avoid duplicate code.
/**
* Get current input from user and try parse it to a number.
*
* #return a number if input is valid, otherwise return null.
*/
private Float getInputValue() {
Float possibleNumber = null;
String numberInString = edt1.getText().toString();
if (isValidNumber(numberInString)) {
possibleNumber = Float.parseFloat(numberInString);
}
return possibleNumber;
}
Third, prevent user from adding more than one zero number by using TextWatcher.
edt1.addTextChangedListener(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) {
String content = s.toString();
if (content.startsWith("0") && content.length() == 2 && Character.isDigit(content.charAt(1))) {
edt1.setText(String.valueOf(content.charAt(1)));
edt1.setSelection(1);
}
}
});
Finally put it together.
public class MainActivity extends AppCompatActivity {
// Your variables here
...
// Make these two variables is Float instead of float.
Float mValueOne;
Float mValueTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Your init view here
...
edt1.addTextChangedListener(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) {
String content = s.toString();
if (content.startsWith("0") && content.length() == 2 && Character.isDigit(content.charAt(1))) {
edt1.setText(String.valueOf(content.charAt(1)));
edt1.setSelection(1);
}
}
});
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueTwo = getInputValue();
if (mValueOne == null || mValueTwo == null) {
// One of there or both of two values are not valid then do nothing.
return;
}
if (mAddition) {
edt1.setText(String.valueOf(mValueOne + mValueTwo));
mAddition = false;
}
if (mSubtract) {
edt1.setText(String.valueOf(mValueOne + mValueTwo));
mSubtract = false;
}
if (mMultiplication) {
edt1.setText(String.valueOf(mValueOne + mValueTwo));
mMultiplication = false;
}
if (mDivision) {
edt1.setText(String.valueOf(mValueOne + mValueTwo));
mDivision = false;
}
}
});
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edt1.setText(String.valueOf(edt1.getText().toString() + "0"));
edt1.setSelection(edt1.getText().length());
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne = getInputValue();
mAddition = true;
edt1.setText(null);
}
});
buttonSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne = getInputValue();
mSubtract = true;
edt1.setText(null);
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne = getInputValue();
mMultiplication = true;
edt1.setText(null);
}
});
buttonDivision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne = getInputValue();
mDivision = true;
edt1.setText(null);
}
});
}
/**
* Get current input from user and try parse it to a number.
*
* #return a number if input is valid, otherwise return null.
*/
private Float getInputValue() {
Float possibleNumber = null;
String numberInString = edt1.getText().toString();
if (isValidNumber(numberInString)) {
possibleNumber = Float.parseFloat(numberInString);
}
return possibleNumber;
}
private boolean isValidNumber(String numberInString) {
try {
Float.parseFloat(numberInString);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
It can't do a
mValueTwo=Float.parseFloat(edt1.getText() + "");
if edt1.getText() is empty.
You can correct this using a try-catch.
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
mValueTwo=Float.parseFloat(edt1.getText() + "");
if (mAddition == true) {
edt1.setText(mValueOne + mValueTwo + "");
mAddition=false;
}
if (mSubtract == true) {
edt1.setText(mValueOne - mValueTwo + "");
mSubtract=false;
}
if (mMultiplication == true) {
edt1.setText(mValueOne * mValueTwo + "");
mMultiplication=false;
}
if (mDivision == true) {
edt1.setText(mValueOne / mValueTwo + "");
mDivision=false;
}
}catch(Exception e){
//eventually logging here
}
}
});
Else you can make some controls before doing the parseFloat
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String edt = edt1.getText().toString();
if(edt.matches("")){
//something like a toast to signal
}else{
mValueTwo=Float.parseFloat(edt1.getText() + "");
if (mAddition == true) {
edt1.setText(mValueOne + mValueTwo + "");
mAddition=false;
}
if (mSubtract == true) {
edt1.setText(mValueOne - mValueTwo + "");
mSubtract=false;
}
if (mMultiplication == true) {
edt1.setText(mValueOne * mValueTwo + "");
mMultiplication=false;
}
if (mDivision == true) {
edt1.setText(mValueOne / mValueTwo + "");
mDivision=false;
}
}
}
});
You can set a hint attribute in your edit text that way it disappears anytime a number is actually inserted.
android:hint="0"
Also for the 0 being in front, maybe you want your edit text to be of the number format
android:inputType = "numberDecimal"
You didn't paste a stacktrace of the crash but I will assume it's a null pointer exception
if (edt1.getText != null) { /* do whatever executions */}

How to display each clicked words from TextView

I am planned to develop an App with very simple concept.The requirement is I want to add a text file from phone(Dynamic, so set span with clickabble position not possible for spannable string) with help of intent chooser. And need to display the selected file content in textView (any view if u suggested).
Once I clicked any of the word from textview content i need display that word in Toast.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showFileChooser();
}
});
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//intent.setType("*/*"); //all files
intent.setType("text/xml"); //XML file only
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 1);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// User pick the file
Uri uri = data.getData();
ExternalFileHandling fileObj=new ExternalFileHandling(getApplicationContext());
String fileContent = fileObj.readTextFile(uri);
aboutTextView.setText(fileContent);
Toast.makeText(this, fileContent, Toast.LENGTH_LONG).show();
} else {
Log.i("data", data.toString());
}
}``
public String readTextFile(Uri uri){
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(Currentcontext.getContentResolver().openInputStream(uri)));
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return builder.toString();
}
[![intent chooser for dynamic file content][1]][1]
Finally I got the Exact answer for my question
aboutTextView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
mOffset = aboutTextView.getOffsetForPosition(motionEvent.getX(), motionEvent.getY());
// mTxtOffset.setText("" + mOffset);
Toast.makeText(HomeScreen.this, findWordForRightHanded(aboutTextView.getText().toString(), mOffset), Toast.LENGTH_SHORT).show();
}
return false;
}
});
private String findWordForRightHanded(String str, int offset) { // when you touch ' ', this method returns left word.
if (str.length() == offset) {
offset--; // without this code, you will get exception when touching end of the text
}
if (str.charAt(offset) == ' ') {
offset--;
}
int startIndex = offset;
int endIndex = offset;
try {
while (str.charAt(startIndex) != ' ' && str.charAt(startIndex) != '\n') {
startIndex--;
}
} catch (StringIndexOutOfBoundsException e) {
startIndex = 0;
}
try {
while (str.charAt(endIndex) != ' ' && str.charAt(endIndex) != '\n') {
endIndex++;
}
} catch (StringIndexOutOfBoundsException e) {
endIndex = str.length();
}
// without this code, you will get 'here!' instead of 'here'
// if you use only english, just check whether this is alphabet,
// but 'I' use korean, so i use below algorithm to get clean word.
char last = str.charAt(endIndex - 1);
if (last == ',' || last == '.' ||
last == '!' || last == '?' ||
last == ':' || last == ';') {
endIndex--;
}
return str.substring(startIndex, endIndex);
}
Here is one more implementation of this functionality
Implement a touch listener with a new class like WordsTouchListener
class WordsTouchListener(
private val text: CharSequence,
private val words: List<CharSequence>,
private val onTargetClicked: (CharSequence) -> Unit,
private val onTextClicked: () -> Unit
) : View.OnTouchListener {
override fun onTouch(view: View, event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_UP) {
val offset = (view as? TextView)?.getOffsetForPosition(event.x, event.y) ?: 0
// You could also add custom delimeters
val target = text.extractWord(offset, ' ', '\n', '\t')
if (target.containsOneOf(*words.toTypedArray())) {
onTargetClicked(target)
} else {
onTextClicked()
}
}
return true
}
}
Extension functions below:
fun Char?.isOneOf(vararg symbols: Char) = symbols.any { this == it }
fun CharSequence.containsOneOf(vararg targets: CharSequence) = targets.any { contains(it) }
fun CharSequence.extractWord(index: Int, vararg delimiters: Char): String {
var startIndex = index
var endIndex = index
while (!getOrNull(startIndex).isOneOf(*delimiters) && startIndex > 0) startIndex--
while (!getOrNull(endIndex).isOneOf(*delimiters) && endIndex < length) endIndex++
return substring(startIndex, endIndex).trim()
}
fun TextView.setWordsClickListener(
words: List<CharSequence>,
onTargetClicked: (CharSequence) -> Unit,
onTextClicked: () -> Unit
) = setOnTouchListener(WordsTouchListener(text, words, onTargetClicked, onTextClicked))
So, now you can just call setWordsClickListener on TextView:
textView.setWordsClickListener(
words = listOf("hello", "world"),
onTargetClicked = {
// Handle specific word clicks
},
onTextClicked = {
// Handle text view clicks
}
)
to prevent exception with previous answer you need to change 1st offset-- to offset=str.lenght()-1 in findWordForRightHanded
I got myself offset much higher then str.lenght()

How to compare String from edittext not less than 10 in 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);

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

Validating multiple EditTexts

Been stuck on this all night and there just doesn't seem to be an easy solution to it. I'm trying to validate all 4 of my fields to ensure that there is a value in each one of them, if there's a value in each one of them after I click the Calculate button a total will be calculated. If any of them don't have a value in them it'll return an error at every EditText which doesn't have a value and a total will not be calculated.
cal.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if( eLoan.getText().toString().length() == 0 )
{
eLoan.setError( "A value is required" );
}
else if( eWage.getText().toString().length() == 0 )
{
eWage.setError( "A value is required" );
}
else if( eGrant.getText().toString().length() == 0 )
{
eGrant.setError( "A value is required" );
}
else if( eOther.getText().toString().length() == 0 )
{
eOther.setError( "A value is required" );
}
else
convertToString();
converToDouble();
inTotal = inLoan + inWage + inGrant + inOther;
DecimalFormat currency = new DecimalFormat(".00");
TotalInNum.setText("£" + currency.format(inTotal));
}
});
I can't get my head around it, I've tried to incorporate a boolean statement to check each EditText but it didn't work either. I'm convinced there's an easier method to do this.
I'm quite new to android, self teaching myself it so I would appreciate it if people could advise me on what I'm doing wrong and maybe give me an example of what I should do.
Thanks to all who respond.
Just to build on what others have said. You can do something like this...
Make a validation method that loops through your EditTexts, checks if they're empty, if true set error and then returns true or false...
public boolean validateEditText(int[] ids)
{
boolean isEmpty = false;
for(int id: ids)
{
EditText et = (EditText)findViewById(id);
if(TextUtils.isEmpty(et.getText().toString()))
{
et.setError("Must enter Value");
isEmpty = true;
}
}
return isEmpty;
}
Make a list of you EditText id's..
int[] ids = new int[]
{
R.id.section1_item1_textfield,
R.id.section1_item2_textfield,
R.id.section1_item3_textfield
};
Now use your validation method to check if empty...
if(!validateEditText(ids))
{
//if not empty do something
}else{
//if empty do somethingelse
}
To use the method above you will need to...
import android.text.TextUtils;
The good thing about doing it this way is that you can simply chuck all of your EditTexts into the list and it does the rest for you. Maintaining a huge chunk of if statements can be annoying and time consuming.
I think the problem is you're missing curlies at the last else, where the logic sits. As it is right now, only convertToString(); is part of that last else and the last four statements will execute no matter what error you're setting.
Try this:
cal.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
boolean failFlag = false;
// TODO Auto-generated method stub
if( eLoan.getText().toString().trim().length() == 0 )
{
failFlag = true;
eLoan.setError( "A value is required" );
}
if( eWage.getText().toString().trim().length() == 0 )
{
failFlag = true;
eWage.setError( "A value is required" );
}
if( eGrant.getText().toString().trim().length() == 0 )
{
failFlag = true;
eGrant.setError( "A value is required" );
}
if( eOther.getText().toString().trim().length() == 0 )
{
failFlag = true;
eOther.setError( "A value is required" );
}
// if all are fine
if (failFlag == false) {
convertToString();
converToDouble();
inTotal = inLoan + inWage + inGrant + inOther;
DecimalFormat currency = new DecimalFormat(".00");
TotalInNum.setText("£" + currency.format(inTotal));
}
}
});
This code will set more than one error, if more exist. Yours will signal only the first found error.
I think the best way to solve this problem is the example below:
private boolean verifyIfEditTextIsFilled(EditText... editText) {
boolean result = true;
for (EditText text : editText) {
if (text.getText().toString().isEmpty()) {
final View focusView = text;
text.setError(getString(R.string.error_required));
focusView.requestFocus();
result = false;
}
}
return result;
}
late answer But may Help someone in need.
Simplest way -->
Create method as below
public Boolean validateUserInput()
{
Boolean isAnyFieldsEmpty=false;
if (position.getText().toString()==null || position.getText().toString().equalsIgnoreCase(""))
{
position.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
position.setError(null);
isAnyFieldsEmpty=false;
}
if (eligiblity.getText().toString()==null || eligiblity.getText().toString().equalsIgnoreCase(""))
{
eligiblity.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
eligiblity.setError(null);
isAnyFieldsEmpty=false;
}
if (skillsRequired.getText().toString()==null || skillsRequired.getText().toString().equalsIgnoreCase(""))
{
skillsRequired.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
skillsRequired.setError(null);
isAnyFieldsEmpty=false;
}
if (desc.getText().toString()==null || desc.getText().toString().equalsIgnoreCase(""))
{
desc.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
desc.setError(null);
isAnyFieldsEmpty=false;
}
if (interviewFrmDate.getText().toString()==null || interviewFrmDate.getText().toString().equalsIgnoreCase(""))
{
interviewFrmDate.setError("choose date");
isAnyFieldsEmpty=true;
}else{
interviewFrmDate.setError(null);
isAnyFieldsEmpty=false;
}
if (interviewToDate.getText().toString()==null || interviewToDate.getText().toString().equalsIgnoreCase(""))
{
interviewToDate.setError("choose date");
isAnyFieldsEmpty=true;
}else{
interviewToDate.setError(null);
isAnyFieldsEmpty=false;
}
if (interviewToTime.getText().toString()==null || interviewToTime.getText().toString().equalsIgnoreCase(""))
{
interviewToTime.setError("choose date");
isAnyFieldsEmpty=true;
}else{
interviewToTime.setError(null);
isAnyFieldsEmpty=false;
}
return isAnyFieldsEmpty;
}
Now on your Button click
call that method as below and validate
#overide
public void onclick
{
Boolean isinputEmpty=validateUserInput()
if(isinputEmpty==false)
{
///process your save or whatever processing it is
}
}

Categories

Resources