Here's the code snippet
s= e1.getText().toString();
iv1 = (ImageView) findViewById(R.id.imageView1);
iv1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(s.matches("")){
int time=2000;
Toast.makeText(Loadscreen.this, "Please specify the level", time).show();
}
else{
int str= Integer.valueOf(s);
if(str>0 && str<11){
calculate(str);
r2=new Random();
int nxt = r2.nextInt(2);
if(nxt==0){
//do some work
}
else{
//do some work
}
}
else{
int time=2000;
Toast.makeText(Loadscreen.this, "Enter a valid level", time).show();
}
}
}
});
Control never goes to the else block. The output on the screen is the text of the Toast with the comment "Please specify the level".
Please suggest why else part is not executed?
probably you are not getting the correct result while getting the text from edit text
write this line in onclick method before any comparison
s= e1.getText().toString();
Related
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);
...
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;
}
}
I'm developing an app which will do multiple method in a single input. For example calculating square circumference and area, I give only one EditText and two button. But when I run the app, if I give an input and click the area button it won't do the calculation until I click the circumference button. And same goes if I change the input. Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.square);
etSide = (EditText) findViewById(R.id.etSquare);
tvResult = (TextView) findViewById(R.id.tvSquare);
Button btnCir = (Button) findViewById(R.id.btnSqrCir);
btnCir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCir();
}
});
Button btnArea = (Button) findViewById(R.id.btnSqrArea);
btnArea.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
countArea();
}
});
}
private void countArea() {
try {
side = etSide.getText().toString();
s = parseInt(side);
area = s * s;
tvResult.setText("Area = " + cir);
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
private void countCir() {
try {
side = etSide.getText().toString();
s = parseInt(side);
cir = 4 * s;
tvResult.setText("Circumference = " + area);
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
Any better idea? Really need help...
It looks like you have your variables backwards. For example:
private void countArea() {
try {
side = etSide.getText().toString();
s = parseInt(side);
area = s * s;
tvResult.setText("Area = " + cir); // <-- here cir doesn't have a value until you click the circumference button
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
So your TextView would display ""Area = ""
It looks to me like you want
tvResult.setText("Area = " + cir);
to be
tvResult.setText("Area = " + area);
Let me know if I'm not understanding you correctly
Note:
For your Toast you should use this or YourActivityName.this for Context instead of getApplicationContext()
One other suggestion I might make since your onClick()s only call a method, to make it simpler you could use one listener like this
public void onCreate(...)
{
...
btnCir.setOnClickListener(this);
btnArea.setOnClickListener(this);
...
}
public void onClick(View v)
{
switch(v.getId()) // get the id of the Button clicked
{
case (R.id.btnSqrArea): // call appropriate method
countArea();
break;
case (R.id.btnSqrCir):
countCir();
break;
}
}
You would just have to remember to add implements OnClickListener to your class definition. That's just a preference but worth mentioning.
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();
}
When I click on button in my program without entering data it shows both errors parallely (I have Highlighted in below prog). here i need to get only one error at a time i mean when it is null it has show appropriate one.vice versa..
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v==findViewById(R.id.button1)) {
et1 = (EditText) findViewById(R.id.editText1);
if(et1.getText()!=null ) {
try {
radius = Double.valueOf(et1.getText().toString());
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
if(radius==0.0) {
Toast.makeText(getApplicationContext(), "Value cannot be 0", Toast.LENGTH_SHORT).show();
}
try {
output = (double) Math.round(Math.PI * radius * radius);
String s = Double.toString(output);
tv1.setText(s);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
}
});
do not make things more complicated as they actually are. You can be sure that a correct value was entered without any try/catch blocks. Possible approach:
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Pattern p = Pattern.compile("([0-9]*)");
if (et1.getText().toString().trim().length() > 0) {
Matcher m = p.matcher(et1.getText().toString().trim());
if (m.matches()) {
radius = Double.valueOf(et1.getText().toString());
output = (double) Math.round(Math.PI * radius
* radius);
tv1.setText(Double.toString(output));
} else
Toast.makeText(getApplicationContext(),
"incorrect value", Toast.LENGTH_SHORT)
.show();
} else
Toast.makeText(getApplicationContext(),
"input is empty", Toast.LENGTH_SHORT).show();
break;
default:
}
}
});
In the above code you check if there was any text entered. The second if checks whether the input is numeric using a java regex. When both requirements are met you can be sure the output is calculated correctly.
BTW, using switch-case is a better approach for click listeners