I cannot find a complete answer for this question so I'll put it again here. I have an EditText, which requires validation every time the user finishes editing. A lot of answers online rely on method editText.setOnEditorActionListener() to detect user pressing Done. However, this methods doesn't detect if the user presses the three hard keys (Back, Home, and the third one). I want to trust the user to always press Done but that's highly unlikely. Please help me out on this issue; and also the name of the third button.
Edit: if there is no validation in place, is there a way to revert all changes made? For example, whenever the user presses BACK, HOME or RECENTS, all changes will be gone?
Try some Like This:
String finalText;
tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
finalText= tv.getText().toString();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
public boolean methodOfValidation(String finalText){
if ( finalText.equals("myCorrectText") )
return true;
else
return false;
}
#Override
public void onDestroy()
{
super.onDestroy();
if(!methodOfValidation(finalText))
Toast.makeText(getApplicationContext(),"ERROR ERROR", toast.LENGTH_SHORT).show();
else
finish();
}
Try validating it in onDestroy and onPause.
When user press HOME (BACK), onPause (onDestroy) will be invoked. So you do something like this there
String text = myEditText.getText().toString();
if (text.equals("")) {
// The EditText is empty. Do nothing.
} else {
// Make the changes here.
}
This is the way u follow ur task.u ll easily validate ur all editText. Inside Button u have to use this.
String grpn=edittext1.getText().toString();
String star=edittext2.getText().toString();
String en=edittext13.getText().toString();
if( grph.equalsIgnoreCase("Select"))
{e`
else if(star.equalsIgnoreCase(""))
{ Toast.makeText(getApplicationContext(), "Set the date", Toast.LENGTH_LONG).show();
}
else if(en.equalsIgnoreCase(""))
{
Toast.makeText(getApplicationContext(), "Please set group no", Toast.LENGTH_LONG).show();
}`
Related
I have a edit text field named as mobile and password and Scenario is that when app launch it appears with error text ,what I want when enter a text in respective field and after completing editing text check with value if correct then move else show error in that field.
code:-
private final BroadcastReceiver m_oOtpReceiver = new BroadcastReceiver() {// creating broadcast to receive otp sent by server from Inbox...
#Override
public void onReceive(Context context, Intent intent) {// on receive method to read OTP sent by server
checkFieldsForEmpty(true);// check whether edit text is empty or not
}
};
private TextWatcher m_oTextWatcher = new TextWatcher() {// making object of TextWathcher class
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {// when text change in Edit tEXT
}
#Override
public void afterTextChanged(Editable s) {
checkFieldsForEmpty(false);// CHECK LOGIN BUTTON DISABLED AND ENABED
}
};
/*This method check Edit text is empty or not*/
public void checkFieldsForEmpty(boolean fromBroadcast) {// this method check Edit text is empty or not
s_szMobileNumber = m_InputMobile.getText().toString().trim();// get mobile number from edit Text
s_szPassword = m_InputPassword.getText().toString().trim();// get password from edit text
if (NetworkUtil.isConnected(getApplicationContext())) {
// if mobile number and password are Emoty
if (s_szMobileNumber != null && s_szMobileNumber.length() > 7 && s_szMobileNumber.length() < 15) {// check if mobile and password is empty ..
if (s_szPassword.length() >= 4 && s_szPassword.length() <= 8) {
m_LoginBtn.setEnabled(true);// make Login button disabled
m_LoginBtn.setBackgroundColor(Color.rgb(0, 80, 147));// set background color on eabled
m_LoginBtn.setOnClickListener(new View.OnClickListener() {// onclick listener on Login Button
#Override
public void onClick(View v) {
postLoginDataToServer();
}
});
} else {
if (!fromBroadcast) {
m_InputPassword.setError("Password must be between 4 to 8 characters long");
}
m_LoginBtn.setEnabled(false);// make login button enabled
m_LoginBtn.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
} else {
if (!fromBroadcast) {
m_InputMobile.setError("Mobile number must be between 7 to 15 characters long");
}
m_LoginBtn.setEnabled(false);// make login button enabled
m_LoginBtn.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
} else {
try {
CSnackBar.getInstance().showSnackBarError(findViewById(R.id.mainLayout), "No Internet Connection Available", getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
m_LoginBtn.setEnabled(false);
m_LoginBtn.setBackgroundColor(Color.rgb(192, 192, 192));
}
}
I can't see where the boolean "fromBroadcast" is either initialised or gets it's state from to know whether that is what you need to check before setting the error message on the textView. From what I have read I would assume you don't need to use an if statement to check "fromBroadcast". The code should work without it. If you are starting the app with an error message and you dont want the error msg then you should check s_szPassword instead of m_InputPassword for input and you can initialise s_szPassword to contain the correct word first so the error msg is not there at the start.
Although code is far from being complete, for the begining I tried to detect via TextWatcher
when character is pressed in EditText that doesn't belong to hex values and not to permit it
to be displayed, but to inform user of error entry.
The excerpt from code follows, where arrayOfChars consists of 16 permitted hex chars and edt2
is EditText var. What I tried is to enter following chars: "aeyd", so it is aim to inform of
"y" as an error and not to display it.
edt2.addTextChangedListener(new TextWatcher(){
private boolean errorDetected= false;
private int oldbefore;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String st;
if (errorDetected){ //set in code bellow
errorDetected= false;
return;
}
st= s.toString();
if (before > 0){
if (before<= s.length()){st= s.subSequence(before, s.length()).toString();}
}
boolean velid= true;
for (char c: st.toCharArray()){
if (new String(arrayOfChars).indexOf(Character.toUpperCase(c))==-1){
edt2.setError("Wrong char - " + c);
errorDetected= true;
oldbefore= before;
velid= false;
break;
}
}
if (velid) {edt2.setError(null);}
}
#Override
public void afterTextChanged(Editable s) {
if (errorDetected){s.delete(oldbefore, s.length());}
}
});
When "y" is entered everything behave as expected- only "ae" displayed and error info also.
However when "d" is entered and breakpoint settled at the beginning of onTextChanged, I see
"s" parameter to be "aeyd"- so "y" is still preserved somehow.
Any help where I go wrong ?
Am developing a hymn app in android, is there a way to let users know that the number they have entered cannot be found in the database, thus the hymn index they entered the hymn is not up to that number immediately the entered it in the edit text.
This is a section of the code
android:ems="10"
android:inputType="number"
android:maxLength="3"`
Restricting length of the EditText could work if your value is inside [-99;999].
Anyway you should read and then validate the number.
EditText.
a. If you have a button (user enters hymn number and clicks a button to find), then add something like this in your onClick method:
Editable e = yourEditText.getText();
String hymnNumberInString = "";
if (e != null) s = hymnNumberInString.toString();
if (hymnNumber.isEmpty()) showEmptyAlert(); //show alert that string is empty;
try {
Integer hymnNumber = Integer.valueOf(s);
if (!findHymn(hymnNumber)) {//here is a search
showErrorMessage();
}
} catch (NumberFormatException e) {
e.printStackTrace();
showErrorMessage();
}
b. If you do not have a button, you can add a TextWatcher and show error if hymn number is exceeded:
yourEditText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#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 (s != null && s.length() != 0) {
try {
Integer hymnNumber = Integer.valueOf(s);
if (findHymn(hymnNumber)) {
//everything is ok, do what you want with it
// BUT!!! Remember that user might entered only 1 and is still entering!
// To ensure that user already entered (or maybe already entered) you can wait for 2 sec.
//E.g. by using someHandler.postDelayed(runnableWithThisCodeInside, 2000);
} else {
showErrorMessage();
}
} catch (NumberFormatException e) {
e.printStackTrace();
showErrorMessage();
}
}
}
});
c. You can use this nice library to simplify proccess of validation.
For predefined set of numbers you can use NumberPicker. This component takes a String array as input (via setDisplayedValues()) - so you can populate it with numbers/string from the database. And its editable (unless you restrict it) - so your user can still enter the number he wants.
is there a way to let users know that the number they have entered cannot be found in the database.
Yes you can do that,Considering you are using EditText to let user enter the number, get the text from there like below
EditText mEdit = (EditText)findViewById(R.id.edittext);
Integer number=Integer.valueOf(editText.getText.toString());
Now you have the number you can run a query on database table to match against the corresponding values, whether it exists in database or not.Something like this
int count= SELECT count(*) FROM tbl_user
WHERE name = ' + number + '
if(count>0){
Log.d("Count","Value exist in database");
}
I have a customized EditText class, whats is happening is that there is a validation already for the field, checking it's length and doing trim.
But, the app is crashing because it is possible to click in the field and insert data after 1 space.
How can I validate when clicking, that user can not write his data? If he/she writes data with one space, the app crashes and I receive the following exception.
java.lang.IllegalArgumentException: Start position must be less than the actual text length
Thanks in advance.
Either you can trim but remember this wont restrict to enter white spaces by user, If you want to restrict white spaces then you need to add filter for your edit text. Adding filter let you restrict what ever character you want to avoid.
P.S - Check for adding filter on given link How do I use InputFilter to limit characters in an EditText in Android?
add "addTextChangedListener" to your EditText and then onTextChanged you can check for your validation. For example,
txtEdit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
String str = s.toString();
if(str.length() > 0 && str.startsWith(" ")){
Log.v("","Cannot begin with space");
txtEdit.setText("");
}else{
Log.v("","Doesn't contain space, good to go!");
}
}
#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
}
});
Get the edit text first by this way:
EditText name=(EditText) findViewById(R.id.txt);
String txtEdit=txt.getEditableText().toString();
then check the text length validation by:
if(txtEdit.length() == 0) {
//your code for what you want to do.
}
trim the string that you get from edit text.
String str=edtext.getText().toString().trim();
if(str!=null && !str.equalsIgnoreCase("")))
{
//perform your operations.
}
else
{
//give error message.
}
I was wondering what is the best way to validate form ?
I did try the following:
EditText fname = (EditText)findViewById(R.id.first_name);
String fname_text = fname.getText().toString;
if(fname_text.equalsIgnoreCase(""))
{
fname.setError("Field is required");
}
and also:
fname.addTextChangedListener(new TextWatcher()
{
#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)
{
Pattern mPattern = Pattern.compile("[A-Za-z]{2,20}$");
Matcher matcher = mPattern.matcher(s.toString());
if(!matcher.matches()) // on Success
{
fname.setError("Please make sure you input a valid first name");
}
}
});
The thing that I am confused in is that ... whenever the page loads for the first time, the error message is shown, but when I go inside the EditText and type some content, and if I erase the content, the error message does not persist. So how do I keep this validation persistent ??? Because the way that the program is shaping up, it looks like it won't validate anything very nicely. And you guys know some good links for regex in android with complete example, please do recommend.
And also, how will me putting the Pattern and Matcher methods in onTextChanged or beforeTextChanged affect the output ?
Instead of running the check right after
EditText fname = (EditText)findViewById(R.id.first_name);
String fname_text = fname.getText().toString;
Use an OnFocusChangeListener and run it whenever the onFocusChange() method is called. Ideally, you'd run it only when the View loses focus. Something like:
EditText fname = (EditText)findViewById(R.id.first_name);
String fname_text = fname.getText().toString;
fname.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean arg1) {
if(!(v.isFocused())) {
//Run your validation
}
}
});
This way, you only run the Validation when the user is done typing, instead of everytime the user changes something.