How to prevent navigation until all validation are fulfill? - android

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();
}

Related

robolectric java.lang.AssertionError while unit testing

I have a login form which contains two edit texts, one to enter an emailId and another to enter a password. I have written a simple method to validate that these fields are not empty. This is my method
public boolean validate() {
if(edtEmail.getText().toString().trim().equalsIgnoreCase("")){
showErrorMessage(true);
return false;
}
if(edtPassword.getText().toString().trim().equalsIgnoreCase("")){
showErrorMessage(false);
return false;
}
return true;
}
I have written a unit test for this method
#Test
public void check_validate() {
EditText edtEmail = loginActivity.findViewById(R.id.edtEmail);
EditText edtPassword=loginActivity.findViewById(R.id.edtPassword);
assertTrue(loginActivity.validate());
}
I am getting the error as java.lang.AssertionError. All i want to check is whether the function is working correctly.

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();
}

Rxjava2 - multi retrofit request and handle all exception

I am new to Rxjava. It is so complex......
I need to handle a complex scenario, I want to know how to make it using Rxjava.
It's a logic about app start:
app start and splash page open
make http reqesut check_update to check if app need update.
if app has new version and must update, pop up a notice dialog with only one update button; if app has new version, but not must update, then pop up a dialog with 2 button(update and ignore); if no new version, go next.
no need to update, so we need to jump to home page or login page, according to current auth_token state.
read auth_token from sharedPreference. then call http request check_auth to check if it is valid or not. if valid, jump to home page; if not, jump to login page.
In this process, 2 http requests and lots of condition checks are involved. http request error also need to be handled, Can this process be written in one Rxjava?
I think I can do it in this way, but I am not sure if it is right.
mRetrofitService.checkUpdate(new CheckUpdateRequest("android", "0.0.1")) // check update request
.compose(RxUtil.applyScheduler()) // scheduler
.flatMap(RxUtil.applyFunction()) // handle the response.
.flatMap((Function<CheckUpdateResponse, ObservableSource<?>>) checkUpdateResponse -> {
int updateMode;
if (checkUpdateResponse.isHas_new_version()) {
if (checkUpdateResponse.isForce_update()) {
updateMode = FORCE_UPDATE; // 1
} else {
updateMode = CHOOSE_UPDATE; // 2
}
} else {
updateMode = NO_UPDATE; // 0
}
return Observable.just(updateMode);
})
.flatMap(o -> {
if (Integer.parseInt(o.toString()) == NO_UPDATE) {
return mRetrofitService.checkAuth();
}
return null; //what should I return for pop up dialog?
})
.flatMap(RxUtil.applyFunction())
.subscribe(new Observer<CheckAuthResponse>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(CheckAuthResponse checkAuthResponse) {
// valid
gotoHome();
}
#Override
public void onError(Throwable e) {
// should I handle pop here?
// should I handle auth invalid here?
// should I handle checkUpdate request error here?
// should I handle checkAuth here?
// how to distinguish these errors?
}
#Override
public void onComplete() {
}
});
Am I right? And would you please answer my questions(comments in the code)?
According to the documentation onError "Notifies the Observer that the Observable has experienced an error condition.". So this callback is not relevant to handle request errors.
I suggest you to use the Response class of retrofit to handle your differents cases.
For example you define your service like that :
#method(url)
Call<CheckAuthResponse> checkUpdate(...);
and in your rx workflow :
mRetrofitService.checkUpdate(new CheckUpdateRequest("android", "0.0.1")) // check update request
.compose(RxUtil.applyScheduler()) // scheduler
.flatMap(RxUtil.applyFunction()) // handle the response.
.map((Function<Response<CheckUpdateResponse>, CheckUpdateResponse>) retrofitResponse -> {
if ( retrofitResponce.code() == authInvalidCode ) {
//do something
} else if (...) {
}
return retrofitResponse.body()
})
.flatMap((Function<CheckUpdateResponse, ObservableSource<?>>) checkUpdateResponse -> {
int updateMode;
if (checkUpdateResponse.isHas_new_version()) {
if (checkUpdateResponse.isForce_update()) {
updateMode = FORCE_UPDATE; // 1
} else {
updateMode = CHOOSE_UPDATE; // 2
}
} else {
updateMode = NO_UPDATE; // 0
}
return Observable.just(updateMode);
})
.flatMap(o -> {
if (Integer.parseInt(o.toString()) == NO_UPDATE) {
return mRetrofitService.checkAuth();
}
return null; //what should I return for pop up dialog?
})
.flatMap(RxUtil.applyFunction())
.subscribe(new Observer<CheckAuthResponse>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(CheckAuthResponse checkAuthResponse) {
// valid
gotoHome();
}
#Override
public void onError(Throwable e) {
// should I handle pop here?
// should I handle auth invalid here?
// should I handle checkUpdate request error here?
// should I handle checkAuth here?
// how to distinguish these errors?
}
#Override
public void onComplete() {
}
});
Hope this helps;
Sorry for my english.

error in applying validation in android application

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

Categories

Resources