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.
Related
I am getting an error when I set the counter to subtract and close the application. I get an error "cannot assign value to final variable counter". If the user logins in 3 times with no success quit the application.
final int counter = 3;
//Set the OKButton to accept onClick
OKButton.setOnClickListener(new View.OnClickListener() {
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
//display text that was inputed for userText and passText
user = userText.getText().toString();
pass = passText.getText().toString();
//create if loop which checks if user and pass equals the credentials
if (user.equals("pshivam") && pass.equals("Bway.857661")) {
//display toast access welcome
String welcome = "Access Granted.";
//Create a Toast to display the welcome string in the MainActivity.
Toast.makeText(MainActivity.this, welcome, Toast.LENGTH_SHORT).show();
setContentView(R.layout.account_main);
}
//create else if loop which checks if user or pass does not equals the credentials
else if (!user.equals("pshivam") || !pass.equals("Bway.857661")){
//displays previous entry
userText.setText(user);
passText.setText(pass);
//allows user to re-enter credentials.
user = userText.getText().toString();
pass = passText.getText().toString();
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}
}
});
}
}
Do something like this :
OKButton.setOnClickListener(new View.OnClickListener() {
int counter = 3;
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
You can also call a function from inside onClick which will decrement the variable, or use a static field declared in your class
This How to increment a Counter inside an OnClick View Event and How do I use onClickListener to count the number of times a button is pressed? might help.
Edit:
What you are doing in else part doesn't make sense. You are setting text for userText and passText that you just got using getText() from these. Then you are storing these same values to user and pass. But you aren't using these variables anywhere and they get new values when onClick is called again. Why not keep it simple :
else {
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}
I am developing an app in which I have two fields: mobile and pass. When a user enters the mobile number, it checks if the mobile number is of ten digit or not. If not, then it should show an error message in the respective field. But here when the app opens, it shows error in the respective fields. How can I solve this problem?
here is code:-
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();// CHECK LOGIN BUTTON DISABLED AND ENABED
}
};
/*This Broadcast receiver will listen network state accordingly
which enable or disable create an account button*/
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();// check whether edit text is empty or not
}
};/*This method check Edit text is empty or not*/
public void checkFieldsForEmpty() {// 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 {
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 {
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));
}
}
This is because of your BroadReceiver is called first time m_oOtpReceiver that is checking network state. and for first time your edit text has no value so length is 0 and it will meet the condition that 0 is not greater that 7 so it will display error first time .
Solution :
If method is called from BroadcastReceiver you dont have to check validation so skip that part.
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(!fromBroadcast){
// check validation
}
else{
// no need to check validation
}
}
from textwatcher
#Override
public void afterTextChanged(Editable s) {
checkFieldsForEmpty(false);// CHECK LOGIN BUTTON DISABLED AND ENABED
}
from broadcast receiver
checkFieldsForEmpty(true);
or you can check whether to display error message.
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 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();
}`
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.
}