App crashes when click with empty text fields - android

I have write a method for register users for backendless. With filled all text fields I can register users. My problem is when when I click button with empty text fields app getting crash, but I wrote a if statement for check empty text fields and show a toast.
public void RegisterButtonPressed(View view) {
if(email.getText() == null || password.getText() == null || username.getText() == null){
Toast.makeText(this, "Every Fileds should be filled", Toast.LENGTH_SHORT).show();
} else {
if(email.getText() != null && password.getText() != null && username.getText() != null) {
final String emailS = email.getText().toString();
final String passwordS = password.getText().toString();
String usernameS = username.getText().toString();
BackendlessUser user = new BackendlessUser();
user.setEmail(emailS);
user.setPassword(passwordS);
user.setProperty("name",usernameS);
user.setProperty("Avatar","");
Backendless.UserService.register(user, new AsyncCallback<BackendlessUser>() {
#Override
public void handleResponse(BackendlessUser backendlessUser) {
Toast.makeText(RegisterActivity.this, "User Registration Successfull", Toast.LENGTH_SHORT).show();
Backendless.UserService.login(emailS, passwordS, new AsyncCallback<BackendlessUser>() {
#Override
public void handleResponse(BackendlessUser backendlessUser) {
Toast.makeText(RegisterActivity.this, "Logged", Toast.LENGTH_SHORT).show();
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
Toast.makeText(RegisterActivity.this, "User Login Unsuccessfull: " + backendlessFault.getDetail(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
Toast.makeText(RegisterActivity.this, "User Registration Unsuccesful: " + backendlessFault.getDetail(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
error log

you should check with
if(TextUtils.isEmpty(email.getText()))
instead of
if (email.getText() == null)
From my experience, the getText() was not return null if it empty, but empty string a.k.a ""
TextUtils.isEmpty() however, will check both null and "" as empty string

You're only checking if the string is null. If it's empty, your if statement will not catch that and could still cause a crash. You should be checking for empty string as well.
if(email.getText() == null || email.getText().length() == 0 ||
password.getText() == null || password.getText.length() == 0 ||
username.getText() == null || username.getText.length() == 0){
Toast.makeText(this, "Every Fileds should be filled", Toast.LENGTH_SHORT).show();
}

This happened with me on AppCompatAutoCompleteTextView, where I have added Spinner Adapter with Filterable.
I have overrided the AppCompatAutoCompleteTextView enoughToFilter() method.
#Override
public boolean enoughToFilter() {
return showAlways || super.enoughToFilter();
}
showAlways is a bool object where I was setting apply a filter with threshold.
As enoughToFilter () => Returns true if the amount of text in the field meets or exceeds the getThreshold() requirement.
On zero-length it was crashing when this showAlways is set to false, just make it to true or
set threshold to 0 & set showAlways to false.

Related

How do i check my password and confirm it with a password in another textbox?

Im making a registration form and we have to enter password and also confirm it, when i execute the code and play in my emulator it gives a toast "Passwords dont match" even though they do match
Here is my coding:
next.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String s1= eml.getText().toString();
String p= ps.getText().toString();
String cp= cps.getText().toString();
String s4= fn.getText().toString();
String s5= bno.getText().toString();
String s6= bname.getText().toString();
String s7= fadd.getText().toString();
if(s1.equals("") || p.equals("") || cp.equals("")|| s4.equals("") || s5.equals("") || s6.equals("")|| s7.equals("")){
Toast.makeText(getApplicationContext(),"Fields are empty",Toast.LENGTH_SHORT).show();
}
else {
if(p.equals(cp)){
Boolean chkmailB= db.chkmailB(s1);
if(chkmailB==true){
Boolean insert= db.insert5(s4,s1,p,s5,s6,s7);
if(insert==true){
Toast.makeText(getApplicationContext(),"Registartion Successful", Toast.LENGTH_SHORT).show();
Intent i= new Intent(bldgmgtm.this, Login.class);
startActivity(i);
}
}
else {
Toast.makeText(getApplicationContext(),"Email already exists",Toast.LENGTH_SHORT).show();
}
}
Toast.makeText(getApplicationContext(),"Passwords dont match",Toast.LENGTH_SHORT).show();
}
}
});```
Add else block after if statement and put Toast in it

Set TextView based on Volley Response in Android

I am using Volley in application.I am getting name,email,phone values from Volley response.The condition is if name and email value is null, I want to set phone value in TextView.If name and phone value is empty, I want to set email in TextView. if phone and email is empty,I want to set name in TeextView.
This is JSON response
{
"id": 25,
"email": "aa#gmail.com",
"phone": null,
"full_name": ""
}
This is how I have parsed JSON
JsonObjectRequest foodie_request = new JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
try {
String fullName = response.getString("full_name");
String phone=response.getString("phone");
String email=response.getString("email");
if(email.trim().equals("") && fullName.trim().equals(""))
{
entry.setName(phone);
}
else if(phone==null && fullName.trim().equals(""))
{
entry.setName(email);
}
else if(email.trim().equals("") && phone==null ) {
entry.setName(fullName);
}
// progressDialog.dismiss();
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
How to do this ?
Check this code:
if(fullName.isEmpty() && fullName != null && email.isEmpty() && email != null)
textView.setText(phone);
if(fullName.isEmpty() && fullName != null && phone.isEmpty() && phone != null)
textView.setText(email);
if(email.isEmpty() && email != null && phone.isEmpty() && phone != null)
textView.setText(fullName);
First of all do not get value null from database according to your question otherwise you will get NullPointerException get a blank string and try this one.
JsonObjectRequest foodie_request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String fullName = response.getString("full_name");
String phone = response.getString("phone");
String email = response.getString("email");
if (fullName.toString().trim().length() == 0 && email.toString().trim().length() == 0) {
entry.setName(phone);
} else if (fullName.toString().trim().length() == 0 && phone.toString().trim().length() == 0) {
entry.setName(email);
} else if (phone.toString().trim().length() == 0 && email.toString().trim().length() == 0) {
entry.setName(fullName);
}
// progressDialog.dismiss();
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Try using this, hope it helps.
if(TextUtils.isEmpty(email) && TextUtils.isEmpty(fullName)) {
entry.setText(phone);
}
else if(TextUtils.isEmpty(phone) && TextUtils.isEmpty(fullName))
{
entry.setText(email);
}
else if(TextUtils.isEmpty(email) && TextUtils.isEmpty(phone)) {
entry.setText(fullName);
}
Try with this, TextUtils.isEmpty(str) also check the null value so no need to further loop.

To check weather string is empty or not

I'm facing a problem to check weather a string is NULL or not in Android. The code is:
if (e1.length() == 0)
Toast.makeText(mainActivity.this, "String is Empty");
its pretty easy
you can do that
if(e1==null || e1.isEmpty){
Toast.makeText(mainActivity.this,"String is Empty");
}
if(TextUtils.isEmpty(yourString)){
//it's empty
}
Try with below code :
if(e1.getText().toString().isEmpty()) {
Toast.makeText(mainActivity.this,"String is Empty");
}
Or,
String ed_text = e1.getText().toString().trim();
if(ed_text.isEmpty() || ed_text.length() == 0 || ed_text.equals("") || ed_text == null)
{
Toast.makeText(mainActivity.this,"String is Empty");
}

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

Login register for android

I'm doing a registration for an android application. Initially, whenever the password and confirm password is not the same, the statement "Password & Confirm Password does not match" will be prompt and it works successfully. However, if the password & Confirm password matches with blanks, this statement should appear, "Do not leave any field empty", unfortunately it fails.
Do help me check for any error.
btn2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
String username, password, cpassword, fullname, nric, address, phone, email;
username = tf3.getText().toString();
password = tf4.getText().toString();
cpassword = tf5.getText().toString();
fullname = tf6.getText().toString();
nric = tf7.getText().toString();
address = tf8.getText().toString();
phone = tf9.getText().toString();
email = tf10.getText().toString();
if(password != cpassword)
{
tv1.setText("Password & Confirm Password does not match.");
}
else if(username.equals("") || password.equals("") || cpassword.equals("") || fullname.equals("") || nric.equals("") || address.equals("") || phone.equals("") || email.equals(""))
{
tv1.setText("Do not leave any field empty.");
}
else
{
try
{
db.beginTransaction();
db.execSQL("insert into Members values('"+username+"','"+password+"','"+fullname+"','"+nric+"','"+address+"','"+phone+"','"+email+"');");
db.setTransactionSuccessful();
db.endTransaction();
}
catch(Exception e)
{
}
tv1.setText("Register Complete.");
}
}
});
You are comparing it in wrong way, just compare your password & Confirm Password as follows,
if(!password.equals(cpassword))
In Java when you want to compare two String variables you need to use equals() method of String class.
btn2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
String username, password, cpassword, fullname, nric, address, phone, email;
username = tf3.getText().toString();
password = tf4.getText().toString();
cpassword = tf5.getText().toString();
fullname = tf6.getText().toString();
nric = tf7.getText().toString();
address = tf8.getText().toString();
phone = tf9.getText().toString();
email = tf10.getText().toString();
if(!password.equals(cpassword)) // Change is here
{
tv1.setText("Password & Confirm Password does not match.");
}
else if(username.equals("") || password.equals("") || cpassword.equals("") || fullname.equals("") || nric.equals("") || address.equals("") || phone.equals("") || email.equals(""))
{
tv1.setText("Do not leave any field empty.");
}
else
{
try
{
db.beginTransaction();
db.execSQL("insert into Members values('"+username+"','"+password+"','"+fullname+"','"+nric+"','"+address+"','"+phone+"','"+email+"');");
db.setTransactionSuccessful();
db.endTransaction();
}
catch(Exception e)
{
}
tv1.setText("Register Complete.");
}
}
});
Compare password and confirm password field as follows.
if(!password.equals(cpassword)){
tv1.setText("Password & Confirm Password does not match.");
}
hope it hepls.. always use equals() to compare two strings.

Categories

Resources