error in applying validation in android application - android

I am developing an android application in which iIhave 4 edittext and below a button. I want to apply validation on each field so that any field is not left blank. I have tried a lot of samples and applied same logic, but its not working.
I have coded for that. My java class is
http://pastebin.com/ZdeYZPxX
But problem is that when I enter first edittext and then click button, it works. Can anyone help me to come out of this problem?

See I have made this function in class
public boolean checkForEmpty(String fieldString) {
if (fieldString.equalsIgnoreCase("")
|| fieldString.equalsIgnoreCase(null))
return true;
else
return false;
}
Then
username = editUserName.getText().toString().trim();
if (checkForEmpty(username)) {
Showalert("Please enter User ID");
editUserName.requestFocus();
}

After showing a Toast telling the user that one of the EditText is empty you should add a return statement to stop the rest of the code(that starts a new Activity) being run until the user fills all EditTexts:
if (un.equals("") || pw.equals("")) {
if (un.equals("")) {
Toast.makeText(BloodPressureScreen.this, "FirstName is empty", Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(BloodPressureScreen.this, "LastName is empty", Toast.LENGTH_SHORT).show();
return;
}
}
if (cn.equals("") || em.equals("")) {
if (cn.equals("")) {
Toast.makeText(BloodPressureScreen.this, "Contact is empty", Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(BloodPressureScreen.this, "Email is empty", Toast.LENGTH_SHORT).show();
return;
}
}

public boolean checkForEmpty(String fieldStr) {
if (fieldStr.length() == 0 )
return true;
else
return false;
}

Related

I got one button here which is submit, and i wanna remind the user to choose an answer with toast so where can i add it?

R.id.btn_submit ->{
if(mSelectedOptionPosition == 0){
mCurrentQuestion++
when{
mCurrentPosition <= mQuestionsList!!.size ->{
setQuestion()
}else ->{
Toast.makeText(this,
"You have successfully completed the quiz",
Toast.LENGTH_SHORT).show()
}
}
}else-> {
val question = mQuestionsList?.get(mCurrentPosition-1)
if (question!!.correctAnswer != mSelectedOptionPosition){
answerView(mSelectedOptionPosition, R.drawable.wrong_option_border_bg)
}
answerView(question.correctAnswer, R.drawable.correct_option_border_bg)
if(mCurrentPosition == mQuestionsList!!.size) {
btn_submit.text = "FINISH"
}else{
btn_submit.text = "Go to next question"
}
}
When do you want to show toast ,you didn't specify clearly.
If you want the user to at least choose an option then simply set a check in the btn_submit clickListener that whether any option is chosen or not ,if not then you can show your toast.
Or you can simply show the toast in
R.id.btn_submit ->{
if(mSelectedOption == null)
{
showToast("your message")
}
else{
if(mSelectedOptionPosition == 0){.....
.
.
.
.
}
this if block and check for it at the first when the block starts assuming if the mSelectedOption is null then no option is selected or else do the rest of the checking..

How to prevent navigation until all validation are fulfill?

I want to add validation to my form. But there is one problem I press submit button it shows the validation for a quick time, and blank form submitted to recyclerview. please give me the solution if you have.
/**
* Performs action to submit the form if all the validations are fulfilled
*/
public void submitForm() {
if (validateFields()) {
//Todo add your form submission code here
}
}
/**
* Validate all the fields present in the form according to the requirements
* Returns true if there is no validation error, false otherwise.
*/
public boolean validateFields() {
if (editTextEmail.getText().toString().isEmpty()) {
//Show toast or snackbar for validation failed
return false;
} else if (//todo another validation code)
{
//Show toast or snackbar for validation failed
return false;
}
return true;
}
Performs action to submit the form if all the validations are fulfilled
public void submitForm() {
if (validateInputFields()) {
//Todo add your form submission code here
}
}
Validate all the fields present in the form according to the requirements
Returns true if there is no validation error, false otherwise.
public boolean validateInputFields() {
if (TextUtils.isEmpty(email)) {
//Show toast or snackbar for validation failed
return false;
}
else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
//Show toast or snackbar for validation failed
return false;
}
else if (//todo another validation code)
{
//Show toast or snackbar for validation failed
return false;
}
return true;
}
You can go like this:
public void clickAction(){
if(validateFields()){
//Todo add your form submission code here
}
}
public boolean validateFields(){
if(editTextEmail.getText().toString().isEmpty()){
//Show toast validation failed
return false;
}else if(//todo another validation code){
return false;
}
return true;
}
Try the below validation method, if it's not working, please share your code here to look further more into your problem.
if (editTextName.getText().toString().trim().length() <= 0 ||
editTextAge.getText().toString().trim().length() <= 0) {
Toast.makeText(LoginActivity.this, "Fields should not be blank",
Toast.LENGTH_LONG).show();
} else {
callSubmitFormApi();
}

Validation android

I'm new in android programming but I have a validation function after the user inserts some data like:source point,destination point,...etc
I have 2 spinners :source and destinations ,both include same values..and i want to be able to send a pop up if a user is selecting the same source and destination and the function is this one:
spSursa=is the source spinner
spDestinatie=is the destinations spinner
private boolean validare_Date()
{
if(spSursa.getSelectedItem().toString()!=spDestinatie.getSelectedItem().toString() )
{
if(ratb.isChecked()==false && metrorex.isChecked()==false && both.isChecked()==false)
{
Toast.makeText(getApplicationContext(), R.string.ADAUGA_RUTA_EROARE_TRANSPORT, Toast.LENGTH_SHORT).show();
return false;
}
else
{
return true;
}
}
else {
Toast.makeText(getApplicationContext(), R.string.ADAUGA_RUTA_EROARE_SURSA_DEST, Toast.LENGTH_SHORT).show();
return false;
}
}
Try to change
if(spSursa.getSelectedItem().toString()!=spDestinatie.getSelectedItem().toString() )
To
if(!spSursa.getSelectedItem().toString().equals(spDestinatie.getSelectedItem().toString()))

validate editText on buttonclick event [duplicate]

This question already has answers here:
Form validation on Button click in android
(3 answers)
Closed 5 years ago.
I am new in android programming and still learning. for practice i started to create a very simple and basic app which calculate age on button click which take birth year as an input.
i manage to get it working and want to do some validation on it. like i have done validating that the value we provide should not be more than current year and i successfully done that.
Now my problem is that i also want to put validation that if no input is been made and button is pressed then it should alert the user by Toast. So far i have tried doing but every time i press button without anything in editText the app just crash.
here's my code.
calcAge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(dob > year){
Toast.makeText(getApplicationContext(), "Provide valid Input", Toast.LENGTH_SHORT).show();
}
else if(String.valueOf(dob) == null){
Toast.makeText(getApplicationContext(), "Please Provide Some Input", Toast.LENGTH_SHORT).show();
}
else{
dob = Integer.parseInt(String.valueOf(inAge.getText()));
currentYear.setText("Your Curret Year is :- " + year);
yourYear.setText("Your Birth Year is :- "+ dob);
int a = year-dob;
finalAns.setText("Your Age is :- " + a);
inAge.setText("");
}
}
});
above code is of button click. Please provide with some solution
I have also tried putting editText1.getText().toString.trim().lenght()==0 in if condition but that also didn't worked and app just crashes.
try this on button click listner
calcAge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (yourEdittext.getText().toString().equals("")) {
yourEdittext.setError(getString("filed can't be empty"));
yourEdittext.requestFocus();
Toast.makeText(getApplicationContext(), "Please Provide Some Input", Toast.LENGTH_SHORT).show();
}
}
});
Use this:
String dob = yourEditText.getText().toString();
then check it like this:
if (TextUtils.isEmpty(dob)) {
//show toast
}
You have to do validation like this :
doneDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(validationDetails()){
//If get all data do Action
}else{
// Toast.makeText(getApplicationContext(),"Field Missing",Toast.LENGTH_SHORT).show();
}
}
This is the validation part method:
private boolean validationDetails() {
if (userNameET.getText().toString().isEmpty()) {
userNameET.setError("Enter Patient Name");
return false;
}
if (ageET.getText().toString().isEmpty()) {
ageET.setError("Enter Age ");
return false;
}
if (gender.getSelectedItem().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"Select Gender",Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
On button click, you are checking first if dob is greater than a year. which is not correct. First, check if dob is null or empty. then check for if greater than year
If (dob == null && dob.isEmplty){
Toast.makeText(getApplicationContext(), "Please Provide Some Input", Toast.LENGTH_SHORT).show();
} else if(dob > year){
Toast.makeText(getApplicationContext(), "Provide valid Input", Toast.LENGTH_SHORT).show();
} else {
//do what ever you want
}
try this on your button click :
if ( yourEditText.getText().toString().equal("")) {
Toast.makeText(getApplicationContext(), "Please Give Some Input", Toast.LENGTH_SHORT).show();
}

Login not working

I have written the simple code for Login authentication with hardcoded password.my problem is evenif I am entering the correct password my control is going in elese loop
edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
s1=edt.getText().toString();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("mynameeeeee",s1);
if(s1=="123")
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
}
});
Here's the problem :
You are storing a reference of the edit text content at creation time, when the edit text is empty.
You should retrieve the content of the edit text EVERYTIME you want to compare, which is when the button is clicked in your case :
Do the following :
edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
btn.setOnClickListener ( new OnClickListener () {
#Override
public void onClick ( View v ) {
Log.d ( "mynameeeeee" , edt.getText().toString() );
if ( edt.getText().toString().equals ( "123" ) )
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
}
});
the string should be compared like:
if(s1.equals("123")) {}
Change your if statement like this
if(s1.equals("123"))
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
When comparing strings always use .equals() function
== Checks whether both the variable are referring to same object. In this case since they are referring to different object so the result of == is false.
use equals() method s1.equals("123") to check the content of the string object.

Categories

Resources