Display toast for empty fields when user submits data - android

I have an activity in which there are three EditTexts: First Name, Middle Name, Last Name, and a Submit button. If the user submits with a field blank, a different toast appears for different field. Here's is an example when button will be clicked!:

I'll assume you can figure out how to use a button listener yourself. Inside that button listener, you can use this code:
// create EditText references
EditText etFirstName = (EditText)findViewById(R.id.firstName);
EditText etMiddleName = (EditText)findViewById(R.id.middleName);
EditText etLastName = (EditText)findViewById(R.id.lastName);
// boolean variables that each represent whether or not the each field is blank
// if the EditText length is 0, it's true (blank); otherwise, it's false (filled)
boolean firstNameBlank = etFirstName.length() == 0;
boolean middleNameBlank = etMiddleName.length() == 0;
boolean lastNameBlank = etLastName.length() == 0;
if (firstNameBlank && middleNameBlank && lastNameBlank) {
// toast all three blank
}
else if (firstNameBlank && middleNameBlank) {
// toast just first and middle are blank
}
else if (firstNameBlank && lastNameBlank) {
// toast just first and last are blank
}
else if (middleNameBlank && lastNameBlank) {
// toast just middle and last are blank
}
else if (firstNameBlank) {
// toast just first is blank
}
else if (middleNameBlank) {
// toast just middle is blank
}
else if (lastNameBlank) {
// toast just last is blank
}
else {
// none are blank
}

Try this way
EditText e = (EditText)findViewById(R.id.EDITTEXT));
if(e.getText().length == 0){
//Show Toast
}else{
//continue your code
}

implement onClick() event of your submit button as below:
#Override
public void onClick(View view) {
super.onClick(view);
switch (view.getId()) {
case R.id.btnSubmit:
if(edtFirstName.getText().toString().length() < 1){
Toast.makeText(this, "please fill all boxes.",Toast.LENGTH_LONG).show();
}else if(edtSecondName.getText().toString().length() < 1){
Toast.makeText(this, "please fill middle name and last name.",Toast.LENGTH_LONG).show();
} else if(edtLastName.getText().toString().length() < 1){
Toast.makeText(this, "please fill last name.",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "please wait...processing.",Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}

Related

Android: Previous page button, without losing data

I have need some help to achieve the following:
When I click on my previous-button I want the application to go to the previous page without losing my data. I already added the previous-button to the application, but when I click it my application goes to the main page instead of the previous page.
My code:
Button next,previous;
next = (Button)findViewById(R.id.work_next);
previous = (Button)findViewById(R.id.work_previous);
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSignUP = new Intent(getApplicationContext(), filldetails.class);
startActivity(intentSignUP);
finish();
}
});
next.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
boolean allValues = true;
String comp="",desg="",fromdate="",todate="",role_d="",technologies_used="";
if(companyName.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
comp= companyName.getText().toString();
//Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
if(designation.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
desg = designation.getText().toString();
//Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
if(fromDate.getText().toString().length()<8 || fromDate.getText().toString().length()>10 ||fromDate.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(),"Please enter valid Date",Toast.LENGTH_SHORT).show();
}
else
{
fromdate = fromDate.getText().toString();
}
if(toDate.getText().toString().length()<8 || toDate.getText().toString().length()>10 ||toDate.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(),"Please enter valid Date",Toast.LENGTH_SHORT).show();
}
else
{
todate = toDate.getText().toString();
}
if(role_desc.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
role_d = role_desc.getText().toString();
}
if(technologiesUsed.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
technologies_used = technologiesUsed.getText().toString();
}
if(allValues)
{
Intent moveToNext = new Intent(getApplicationContext(),skills.class);
moveToNext.putExtra("comp_name",comp);
moveToNext.putExtra("desc",desg);
moveToNext.putExtra("role_d",role_d);
moveToNext.putExtra("from_date",fromdate);
moveToNext.putExtra("to_date",todate);
moveToNext.putExtra("technologies_used",technologies_used);
moveToNext.putExtra("iscurrent",isCurrent.isChecked());
moveToNext.putExtra("aboutme",getIntent().getStringExtra("aboutme"));
moveToNext.putExtra("address",getIntent().getStringExtra("address"));
startActivity(moveToNext);
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Please provide all values", Toast.LENGTH_SHORT).show();
}
}
});
}
You don't need to start the activity to go to previous activity (if you haven't called finish() on that), just close the current activity and it will go to previous activity and data will be intact.
Change your onClick method of previous button like this
#Override
public void onClick(View v) {
finish();
}
Note: If you have closed the previous activity by calling finish() then remove that code, otherwise data will not be intact without modifying your code in that activity.

how to check if edittext is empty?

I have a sign up form that asking the users to enter a username and a password twice, I want to don't submit the form and alert the user if he messes to fill any of the fields, but the button is not working in all cases, this is my code:
user = (EditText) this.findViewById(R.id.username);
pass = (EditText) this.findViewById(R.id.password);
pass2 = (EditText) this.findViewById(R.id.password2);
u = user.getText().toString();
p1 = pass.getText().toString();
p2 = pass2.getText().toString();
if(!(u.equals("")||p1.equals("")||p2.equals(""))){
btn = (Button) this.findViewById(R.id.register2);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!p1.equals(p2))
Toast.makeText(getApplicationContext(), "Passwords didn't match!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "Passwords match!", Toast.LENGTH_SHORT).show();
}
});
}
Remove this if condition line
if(!(u.equals("")||p1.equals("")||p2.equals(""))){
And put this inside the click lisner
if(!(u.equals("")||p1.equals("")||p2.equals(""))){
//Toast message please enter the username or pwd
return;
}
I found the ideal answer is make a method as follow:
boolean isEmpty(EditText e){
return e.getText().toString().trim().length() == 0;
}
Simple way is check the length of the EditText box content
EditText resultInput = (EditText)findViewById(R.id.result);
if(resultInput.getText().length() > 0)
// Edit Text is Empty
else
// Edit Text is Empty
if(!(user.getText().length() <= 0) & (pass.getText().length() <= 0) & (pass2.getText().length() <= 0))){
btn = (Button) this.findViewById(R.id.register2);
...

Android: check the edit text isempty and submit issue

In my app i have dailog with edittext and submit button, if the edittext is empty
i gave a toast message "please enter something" ..my code is below
Button reviewPost = (Button) dialog.findViewById(R.id.submit);
reviewPost.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
v.setEnabled(false);
EditText ratingComment = (EditText) dialog
.findViewById(R.id.reviewcomment);
String comment = ratingComment.getText().toString();
String postStatus = "Y";
if (spinner.getSelectedItemPosition() > 0) {
postStatus = "N";
}
RadioGroup rating = (RadioGroup) dialog
.findViewById(R.id.customrating);
int radioButtonID = rating.getCheckedRadioButtonId();
View radioButton = rating.findViewById(radioButtonID);
int ratingNo = rating.indexOfChild(radioButton);
String ratingValue = (ratingNo + 1) + "";
if (comment != null && !comment.equalsIgnoreCase("")){
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
activity.finish();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}
Constants.rivewDialog = new ProgressDialog(activity);
Constants.rivewDialog.setCanceledOnTouchOutside(false);
Constants.rivewDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Constants.rivewDialog.setMessage(activity.getString(R.string.postingrivew));
Constants.rivewDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Constants.rivewDialog.show();
dialog.dismiss();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
But even if the edittext is empty it is submitting which should not happen.i am checking the condition as follows but its not working
if (comment != null && !comment.equalsIgnoreCase("")){
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
activity.finish();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}
use comment.trim().equals("") instead of comment.equalsIgnoreCase("")
or put a check on comment string length that it should exceed the minimum characters.
use
if(comment != null && !comment.isEmpty())
You can used this.
if(comment != null && !comment.isEmpty() && comment.length()!=0){
//your task
}else{
//give some message
}
Solved with below code..the problem is with the v.setEnabled(false);...i moved it into the if condition
if (comment != null && !comment.equalsIgnoreCase("")){
v.setEnabled(false);
new PostReviewMessage().execute(activity, comment,
ratingValue, postStatus);
Constants.rivewDialog = new ProgressDialog(activity);
Constants.rivewDialog.setCanceledOnTouchOutside(false);
Constants.rivewDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Constants.rivewDialog.setMessage(activity.getString(R.string.postingrivew));
Constants.rivewDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
}
});
Constants.rivewDialog.show();
dialog.dismiss();
}else{
Toast.makeText(activity, "Please enter your comment", Toast.LENGTH_SHORT).show();
}

Android - Activity doesn't reach onSaveInstanceState

I have an Android application that simply saves data and displays them in a list view, very similar to the Notepad tutorial. Unfortunately my Add activity seems to have stopped working somewhere along the line. When I attempt to add data and press Confirm, it reloads the Activity (the screen flickers slightly) and any data I have entered into the fields is cleared . I have confirmed that it is not reaching onSaveInstanceState(). I was under the impression that this method was called automatically upon finish(), and like I mentioned it was working at one time. Maybe someone can spot where I have introduced an error into my code? I'll paste what I believe are the relevant parts:
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Verify that fields are filled out
String description = mDescriptionText.getText().toString();
String amount = mAmountText.getText().toString();
if(description.length() == 0 || amount.length() == 0) {
if(description.length() == 0) {
Context context = getApplicationContext();
CharSequence text = "A description is required";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else {
Context context = getApplicationContext();
CharSequence text = "An amount is required";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
else {
/* Call this to set the result that your activity will return to its caller */
setResult(RESULT_OK);
/* Call this when your activity is done and should be closed. The ActivityResult is propagated back to
whoever launched you via onActivityResult() */
finish();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.i("expEdit","onSaveInstance State Reached");
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(EZBudgetDbAdapter.KEY_ROWID, mRowId);
}
private void saveState() {
Log.i("expEdit","saveState Reached");
String description = mDescriptionText.getText().toString();
String amount = mAmountText.getText().toString();
Double dAmount = 0.0;
if(amount != "") {
dAmount = Double.valueOf(amount).doubleValue();
}
if (mRowId == null) {
long id = mExpDbHelper.createExpenditure(description, dAmount);
if (id > 0) {
mRowId = id;
}
if (mSaveDesc.isChecked()) {
// Save the description to the CommonDesc table
mCommDbHelper = new CommonDescDbAdapter(this);
mCommDbHelper.open();
mCommDbHelper.createCommonDesc(description);
}
} else {
mExpDbHelper.updateExpenditure(mRowId, description, dAmount);
if (mSaveDesc.isChecked()) {
// Save the description to the CommonDesc table
mCommDbHelper = new CommonDescDbAdapter(this);
mCommDbHelper.open();
mCommDbHelper.createCommonDesc(description);
}
}
}
onSaveInstanceState() is not called after finish(). See following onSaveInstanceState
and your code is not clean. Never duplicate code for nothing. You should use
Context context = getApplicationContext();
CharSequence text;
int duration = Toast.LENGTH_SHORT;
if(description.length() == 0) {
text = "A description is required";
} else {
text = "An amount is required";
}
Toast toast = Toast.makeText(context, text, duration);
toast.show();

Advice needed with edit text fields

Hey guys I have an Activity with some EditText fields.
The user needs to fill up all the text fields before pressing the save Button.
Here is what I thought would work. I checked the texts entered in the EditText fields, if the text is not null, then the respective data is saved in
the data base, but if the text is null, a Toast is displayed displaying a message to re enter the text. here's the code:
account_Number.setText(null);
customer_Number.setText(null);
account_Holder.setText(null);
bank_Name.setText(null);
branch_Name.setText(null);
branch_Address.setText(null);
Ifsc.setText(null);
Micr.setText(null);
current_Balance.setText(null);
AddAccount = (Button) findViewById(R.id.addAccount);
AddAccount.setOnClickListener(this);
}
// only after all the fields have been filled, should the message data added
// successfully be displayed.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.addAccount:// try making the user enter in all the fields
boolean work = true;
if (account_Number.getText() != null
&& customer_Number.getText() != null
&& account_Holder.getText() != null
&& bank_Name.getText() != null
&& branch_Name.getText() != null
&& branch_Address.getText() != null
&& Ifsc.getText() != null && Micr.getText() != null
&& current_Balance.getText() != null) {
try {
String accountNumber = account_Number.getText().toString();
String customerNumber = customer_Number.getText()
.toString();
String accountHolder = account_Holder.getText().toString();
String bankName = bank_Name.getText().toString();
String branchName = branch_Name.getText().toString();
String branchAddress = branch_Address.getText().toString();
String ifsc = Ifsc.getText().toString();
String micr = Micr.getText().toString();
String currentBalance = current_Balance.getText()
.toString();
DatabaseClass entry = new DatabaseClass(AddnewAccount.this);
entry.open();
entry.createEntry(accountNumber, customerNumber,
accountHolder, bankName, branchName, branchAddress,
ifsc, micr, currentBalance);
} catch (Exception e) {
work = false;
Dialog message = new Dialog(this);
message.setTitle("Error");
String error = e.toString();
TextView tv = new TextView(this);
tv.setText(error);
message.setContentView(tv);
message.show();
} finally {
Toast message = Toast.makeText(AddnewAccount.this,
"Data Added Successfully", Toast.LENGTH_SHORT);
message.show();
Intent goBackHome = new Intent(AddnewAccount.this,
AccountManagerActivity.class);
startActivity(goBackHome);
finish();
}
} else {
Toast message = Toast.makeText(AddnewAccount.this, // not getting executed
"Please Fill All The Fields", Toast.LENGTH_LONG);
message.show();
Intent refill = new Intent(AddnewAccount.this,
AddnewAccount.class);
startActivity(refill);
finish();
}
break;
}
}
A blank EditText field does not return null for getText(), but rather returns "".
Just check if .getText().toString().trim().equals("") for each field.
check like,,,
String a_number = account_Number.getText().tostring().trim();
String c_number = customer_Number.getText().tostring().trim();
if(TextUtils.isEmpty(a_number) || TextUtils.isEmpty(c_number)){
Toast.makeText(AddnewAccount.this,
"Please Fill All The Fields", Toast.LENGTH_LONG).show();
}else{
//Nothing is empty...
}

Categories

Resources