To check weather string is empty or not - android

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

Related

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.

App crashes when click with empty text fields

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.

String doesn't compare

I have a method where i compare two string, but they dont compare the right way. For example I have this:
dropdown.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
String selectedRate = data[i];
if (!data[i].equals("")) {
showSubQuestion(selectedRate);
} else {
selectedRate = "";
}
where data[i] is also and string and then it continues to:
showSubQuestion(String selectedValue){
...
String selectedValueId = selectedValue;
if (selectedValueId.equals("2459") && selectedValueId.equals("2460")) {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("2");
myTextViews[j].setText(surveyArray[0].getQuestions()[1].getText());
}
if (selectedValueId.equals("2461") && selectedValueId.equals("2462")) {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("3");
myTextViews[j].setText(surveyArray[0].getQuestions()[2].getText());
} else {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("4");
myTextViews[j].setText(surveyArray[0].getQuestions()[3].getText());
}
}
where selected value is ex: 2461 but it doesnt enters i the secont IF.
What am I doing wrong?
Here's part of the JSON:
"question_choices":[
{
"id":2459,
"label":"10 - highly likely",
"value":"10"
},
{
"id":2460,
"label":"9",
"value":"9"
},
{
"id":2461,
"label":"8",
"value":"8"
String selectedValueId = selectedValue;
if (selectedValueId.equals("2459") || selectedValueId.equals("2460")) {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("2");
myTextViews[j].setText(surveyArray[0].getQuestions()[1].getText());
}
if (selectedValueId.equals("2461") || selectedValueId.equals("2462")) {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("3");
myTextViews[j].setText(surveyArray[0].getQuestions()[2].getText());
} else {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("4");
myTextViews[j].setText(surveyArray[0].getQuestions()[3].getText());
}
}
Replace this code & Try this out it will work
Your conditions are incorrect
if (selectedValueId.equals("2461") && selectedValueId.equals("2462"))
you should replace && with ||
Your value can't be 2461 AND 2462 at the same time
May be you want to use || instead of &&

Settings Non-English language password on android phone?

With Reference to this question on android stack, i have a solution to do which allows android phone to provide support for setting non-english language password.
My phones SRC is based on stock-android which is not allowing me to set password which is non-ascii standards like Hebrew.
Based from AOSP source code that handles the password input for lock screen, ChooseLockPassword.java, inside validatePassword() (line 292), here is a snippet that will show the "illegal character" message (from line 311):
// allow non control Latin-1 characters only
if (c < 32 || c > 127) {
return getString(R.string.lockpassword_illegal_character);
}
I have commented out this part but i don't think so this will work. [Waiting to be Flashed]
There are no such question for this condition, i need help for cracking the possibility for doing this any "Work around" will also do.
So after fighting few days i got a workaround by implementing my method for it.
private String validateHebrewPassword(String password)
{
if (password.length() < mPasswordMinLength) {
return getString(mIsAlphaMode ?
R.string.lockpassword_password_too_short
: R.string.lockpassword_pin_too_short, mPasswordMinLength);
}
if (password.length() > mPasswordMaxLength) {
return getString(mIsAlphaMode ?
R.string.lockpassword_password_too_long
: R.string.lockpassword_pin_too_long, mPasswordMaxLength + 1);
}
for (int i = 0; i < password.length(); i++)
{
char c = password.charAt(i);
System.out.println("Validate Hebrew Password Success "+ " Char "+c+" for password "+password+ " langauage "+locale);
}
return null;
}
And modiying its validatePasswor() caller a bit specific to hebrew like:
private void handleNext() {
final String pin = mPasswordEntry.getText().toString();
if (TextUtils.isEmpty(pin)) {
return;
}
String errorMsg = null;
if (mUiStage == Stage.Introduction)
{
String locale = java.util.Locale.getDefault().getLanguage();
if(locale.equals("iw")) //Specific Hebrew check
{
errorMsg = validateHebrewPassword(pin); //New Method
}
else
{
errorMsg = validatePassword(pin); //AOSP Method
}
if (errorMsg == null)
{
mFirstPin = pin;
mPasswordEntry.setText("");
updateStage(Stage.NeedToConfirm);
}
} else if (mUiStage == Stage.NeedToConfirm) {
if (mFirstPin.equals(pin)) {
final boolean isFallback = getActivity().getIntent().getBooleanExtra(
LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false);
mLockPatternUtils.clearLock(isFallback);
mLockPatternUtils.saveLockPassword(pin, mRequestedQuality, isFallback);
getActivity().setResult(RESULT_FINISHED);
getActivity().finish();
} else {
CharSequence tmp = mPasswordEntry.getText();
if (tmp != null) {
Selection.setSelection((Spannable) tmp, 0, tmp.length());
}
updateStage(Stage.ConfirmWrong);
}
}
if (errorMsg != null) {
showError(errorMsg, mUiStage);
}
}
private void updateUi() {
String password = mPasswordEntry.getText().toString();
final int length = password.length();
if (mUiStage == Stage.Introduction && length > 0) {
if (length < mPasswordMinLength) {
String msg = getString(mIsAlphaMode ? R.string.lockpassword_password_too_short
: R.string.lockpassword_pin_too_short, mPasswordMinLength);
mHeaderText.setText(msg);
mNextButton.setEnabled(false);
} else
{
String locale = java.util.Locale.getDefault().getLanguage();
String error = null;
if(locale.equals("iw")) //Specific Hebrew check
{
error = validateHebrewPassword(password); //New method
}
else
{
error = validatePassword(password); //AOSP Method
}
if (error != null) {
mHeaderText.setText(error);
mNextButton.setEnabled(false);
} else {
mHeaderText.setText(R.string.lockpassword_press_continue);
mNextButton.setEnabled(true);
}
}
} else {
mHeaderText.setText(mIsAlphaMode ? mUiStage.alphaHint : mUiStage.numericHint);
mNextButton.setEnabled(length > 0);
}
mNextButton.setText(mUiStage.buttonText);
}

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

Categories

Resources