Checkboxes and if-else statements - java

This is the source for a small app I'm making in Android Studio. When I call this function its suppose to compare dog,cat, and parrot to each other and then increment int dogCounter by 5. When I run the function however, It does not update the score.
dogCounter= 0;
catCounter = 0;
//check boxes
cutestCheckBoxDog = (CheckBox)findViewById(R.id.CheckboxCutestDog);
cutestCheckBoxCat = (CheckBox)findViewById(R.id.CheckboxCutestCat);
cutestCheckBoxParrot =(CheckBox)findViewById(R.id.CheckboxCutestParrot);
//call methods
processCutest(cutestCheckBoxDog, cutestCheckBoxCat, cutestCheckBoxParrot);
showResultButton= (Button)findViewById(R.id.showResults);
showResultButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),catCounter + " " + dogCounter, Toast.LENGTH_LONG).show();
public void processCutest(CheckBox dog, CheckBox cat, CheckBox parrot){
if (dog.isChecked() && !cat.isChecked() && !parrot.isChecked()){
dogCounter += 5;
}else if (cat.isChecked() && !dog.isChecked() && !parrot.isChecked()){
catCounter += 5;
} else{
//nobody gets points
}
}
edit: Sorry for poor organization. Still pretty new, pointers on that would be nice as well.
package dogorcatperson.ivellapplication.com.dogorcatperson;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private RadioGroup canineRadioGroup;
private RadioButton canineRadioButton;
private SeekBar seekBar;
private TextView seekBarTextView;
private CheckBox cutestCheckBoxDog;
private CheckBox cutestCheckBoxCat;
private CheckBox cutestCheckBoxParrot;
private RadioGroup droolRadioGroup;
private RadioButton droolRadioButton;
private Button showResultButton;
private int dogCounter;
private int catCounter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//call setup()
setUp();
//seekbar
seekBar = (SeekBar) findViewById(R.id.seekBarFeline);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekBarTextView.setText("comfortableness: " + progress + "/" + seekBar.getMax());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public void setUp(){
dogCounter= 0;
catCounter = 0;
canineRadioGroup =(RadioGroup)findViewById(R.id.radioGroupCanine);
droolRadioGroup = (RadioGroup)findViewById(R.id.RadioGroupDrool);
seekBarTextView = (TextView)findViewById(R.id.seekBarProgressTextView);
//check boxes
cutestCheckBoxDog = (CheckBox)findViewById(R.id.CheckboxCutestDog);
cutestCheckBoxCat = (CheckBox)findViewById(R.id.CheckboxCutestCat);
cutestCheckBoxParrot = (CheckBox)findViewById(R.id.CheckboxCutestParrot);
//call methods
processCutest(cutestCheckBoxDog, cutestCheckBoxCat, cutestCheckBoxParrot);
processDrool(droolRadioGroup);
processCanine(canineRadioGroup);
showResultButton= (Button)findViewById(R.id.showResults);
showResultButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),catCounter + " " + dogCounter, Toast.LENGTH_LONG).show();
// Intent i = new Intent(MainActivity.this, ResultActivity.class);
// i.putExtra("catCounter", catCounter);
// i.putExtra("dogCounter", dogCounter);
// startActivity(i);
}
});
}
public void processCutest(CheckBox dog, CheckBox cat, CheckBox parrot){
if (dog.isChecked() && !cat.isChecked() && !parrot.isChecked()){
dogCounter += 5;
}else if (cat.isChecked() && !dog.isChecked() && !parrot.isChecked()){
catCounter += 5;
} else{
//nobody gets points
}
}
public void processDrool(final RadioGroup radioGroup){
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int radioId= radioGroup.getCheckedRadioButtonId();
droolRadioButton = (RadioButton)findViewById(radioId);
if (droolRadioButton.getText().equals("yes")){
dogCounter+= 5;
}else if (droolRadioButton.getText().equals("no")){
catCounter+= 5;
}
}
});
}
public void processCanine(final RadioGroup radioGroup){
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int radioId= canineRadioGroup.getCheckedRadioButtonId();
canineRadioButton = (RadioButton)findViewById(radioId);
if (canineRadioButton.getText().equals("yes")){
catCounter+= 5;
}else if (canineRadioButton.getText().equals("no")){
dogCounter+= 5;
}
}
});
}
}

I think you just need to change your processCutest call so that it goes inside the onClick method, but before the toast.makeText call. Like this:
showResultButton= (Button)findViewById(R.id.showResults);
showResultButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
processCutest(cutestCheckBoxDog, cutestCheckBoxCat, cutestCheckBoxParrot);
Toast.makeText(getApplicationContext(),catCounter + " " + dogCounter, Toast.LENGTH_LONG).show();
I'm assuming that the actual checkboxes are defined elsewhere. Are your checkboxes showing up? If so you might want to put the processDrool and processCanine calls right there as well.

Related

android edittext (Number validation) cannot return value from a method with void result type

package com.example.crazywriteup.getbmi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MaleActivity extends AppCompatActivity
{
EditText enm,ehgf,ehgi,ewg;
Button btnmale;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_male);
enm = (EditText)findViewById(R.id.mleditText);
ehgf = (EditText)findViewById(R.id.mleditText2);
ehgi = (EditText)findViewById(R.id.mleditText3);
ewg = (EditText)findViewById(R.id.mleditText4);
btnmale = (Button)findViewById(R.id.btnmlsubmit);
btnmale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(enm.getText().toString().isEmpty())
{
Toast toast = Toast.makeText(getApplicationContext(), "PLS FILL NAME",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 0);
toast.show();
}
else
{
// Nothing
ehgf.requestFocus();
}
}
});
public boolean isNum(String val)
{
boolean check = false;
String no = "\\d*\\.?\\d+";
CharSequence inputstr = val;
Pattern pte = Pattern.compile(no,Pattern.CASE_INSENSITIVE);
Matcher matcher = pte.matcher(inputstr);
if(matcher.matches())
{
check = true;
}
return check;
}
}
}
I am working on android number textbox () I want to set the range 1 to 7 but I am facing difficulty in programming code. It always shows the error cannot return a value from a method with void result type. I am a beginner & don't have much knowledge about programming.
The onCreate() method return void and you are trying to return boolean
You need to create your isNum() method outside the onCreate()
SAMPLE CODE
public class MaleActivity extends AppCompatActivity
{
EditText enm,ehgf,ehgi,ewg;
Button btnmale;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_male);
enm = (EditText)findViewById(R.id.mleditText);
ehgf = (EditText)findViewById(R.id.mleditText2);
ehgi = (EditText)findViewById(R.id.mleditText3);
ewg = (EditText)findViewById(R.id.mleditText4);
btnmale = (Button)findViewById(R.id.btnmlsubmit);
btnmale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(enm.getText().toString().isEmpty())
{
Toast toast = Toast.makeText(getApplicationContext(), "PLS FILL NAME",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 0);
toast.show();
}
else
{
// Nothing
ehgf.requestFocus();
}
}
});
}
public boolean isNum(String val)
{
boolean check = false;
String no = "\\d*\\.?\\d+";
CharSequence inputstr = val;
Pattern pte = Pattern.compile(no,Pattern.CASE_INSENSITIVE);
Matcher matcher = pte.matcher(inputstr);
if(matcher.matches())
{
check = true;
}
return check;
}
}

Running animation after animation, android studio

I am new at android programming and I have a problem to run animation after animation in android studio. The thing is that I don't have specified number of animations I need, it depends on counter.
package com.example.smartpc.memorygame;
import android.graphics.drawable.TransitionDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.Random;
public class MemoryGame extends AppCompatActivity {
ImageView imgRed;
ImageView imgGreen;
ImageView imgBlue;
Button btnStart;
ArrayList<Integer>array=new ArrayList<>();
int counter=3;
int i=0;
Boolean flag=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory_game);
imgRed=(ImageView)findViewById(R.id.imgRed);
imgGreen=(ImageView)findViewById(R.id.imgGreen);
imgBlue=(ImageView)findViewById(R.id.imgBlue);
btnStart=(Button)findViewById(R.id.btnStart);
final RotateAnimation animation=new RotateAnimation(0f,360f, RotateAnimation.RELATIVE_TO_SELF,0.5f,
RotateAnimation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(1000);
// animation.setRepeatCount(1);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
;
}
#Override
public void onAnimationEnd(Animation animation) {
if (flag==true) {
i++;
Random rand = new Random();
int number = Math.abs(rand.nextInt() % 3);
btnStart.setText(Integer.toString(i) + " " + Integer.toString(number));
if (number == 0) {
imgRed.startAnimation(animation);
} else if (number == 1) {
imgGreen.startAnimation(animation);
} else if (number==2){
imgBlue.startAnimation(animation);
}
if (i == counter - 1) {
i = 0;
flag=false;
return;
}
}
}
#Override
public void onAnimationRepeat(Animation animation) {
;
}
});
imgRed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgRed.startAnimation(animation);
flag=false;
}
});
imgGreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgGreen.startAnimation(animation);
flag=false;
}
});
imgBlue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgBlue.startAnimation(animation);
flag=false;
}
});
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// imgGreen.setImageResource(R.drawable.transition);
// ((TransitionDrawable) imgGreen.getDrawable()).startTransition(3000);
flag=true;
Random rand = new Random();
int number = Math.abs(rand.nextInt() % 3);
if (number == 0) {
imgRed.startAnimation(animation);
}
else if (number == 1) {
imgGreen.startAnimation(animation);
}
else if (number==2) {
imgBlue.startAnimation(animation);
}
// btnStart.setText(Integer.toString(i) + " " + Integer.toString(number));
}
});
}
}
In method onAnimationEnd() is problem. It generates number and starts good animaton, but it also starts another one (random, there's no rule which one). Does anyone have idea how to solve this? Also, counter is not fixed, I want to change it in code later.
I will try my best to explain it.
When the process run into onAnimationEnd(), it does mean the animation is finished. It just like to wait for the onAnimationEnd(). And then you call startAnimation(sameAnimation), we can see the method source code.
/**
* Start the specified animation now.
*
* #param animation the animation to start now
*/
public void startAnimation(Animation animation) {
animation.setStartTime(Animation.START_ON_FIRST_FRAME);
setAnimation(animation);
invalidateParentCaches();
invalidate(true);
}
Notice this code : animation.setStartTime(Animation.START_ON_FIRST_FRAME);
If you set the start time with -1, the animation we have run previously will be reset. Oops, because we said the animation is not really finished, it will rerun as the last time.
Run your progress, if you see there are two images rotating at the same time, one of them must be the last one which has rotated.
If you want to run animation after animation, you may not use the same animation in onAnimationEnd(). Or you can use View.clearAnimation() to clear all animation which attach to the view.
I'm glad if it could help you. And if there is anything wrong, please add a comment.

TextWatcher implementation with RadioButtons

Please see attached image and code snippet to aid in explanation.
From the attached image I would like the user to enter a cost, quantity and select either Include Tax or Exclude tax and a new cost is automatically generated where indicated without pressing a Button, but to no avail I am unable to do this. Someone please help. Thanks
See Image Here
After implementing the Changes that were suggested and trying to enter an input in the cost field I was met with the error seen below. Please provide additional feedback. Thanks
Error image
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class Calculator extends Fragment {
private static EditText itemText, editCost, editQuantity, calCost, rTax;
private static RadioGroup rGroup;
private static RadioButton rb;
View gView;
private double bTotal = 0, aTotal = 0, trueCost = 0, taxValue = 16.5, cost = 0, newCost = 0;
private int quantity = 1;
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.US);
DecimalFormat decimalFormat = new DecimalFormat("###,###.##", symbols);
CalculatorListener activityCommander;
public interface CalculatorListener {
void addtoCart(String itemName, int qty, double beforeTax, double afterTax, double bTotal, double aTotal);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
activityCommander = (CalculatorListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString());
}
}
public Calculator() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
gView = inflater.inflate(R.layout.fragment_calculator, container, false);
editCost = (EditText) gView.findViewById(R.id.editcost);
itemText = (EditText) gView.findViewById(R.id.itemText);
editQuantity = (EditText) gView.findViewById(R.id.editquantity);
calCost = (EditText) gView.findViewById(R.id.calcost);
rTax = (EditText) gView.findViewById(R.id.rtax);
rGroup = (RadioGroup) gView.findViewById(R.id.rgroup);
final ImageButton FieldButton = (ImageButton) gView.findViewById(R.id.FieldButton);
final ImageButton TaxButton = (ImageButton) gView.findViewById(R.id.TaxButton);
final ImageButton CalButton = (ImageButton) gView.findViewById(R.id.CalButton);
rTax.setEnabled(false);
calCost.setEnabled(false);
rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rb = (RadioButton)gView.findViewById(checkedId);
}
});
editCost.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
try{
update();
}catch (NumberFormatException e)
{
e.printStackTrace();
}
}
});
editQuantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
try{
update();
}catch (NumberFormatException e)
{
e.printStackTrace();
}
}
});
FieldButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
clearfield();
}
}
);
TaxButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
adjtax();
}
}
);
CalButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
//toCart();
}
}
);
return gView;
}
public void clearfield() {
editCost.setText("");
editCost.setBackgroundResource(R.drawable.edittxt);
editQuantity.setText("");
editQuantity.setBackgroundResource(R.drawable.edittxt);
calCost.setText("");
calCost.setBackgroundResource(R.drawable.edittxt);
itemText.setText("");
itemText.setBackgroundResource(R.drawable.edittxt);
rGroup.clearCheck();
}
public void adjtax() {
editCost.setBackgroundResource(R.drawable.edittxt);
editQuantity.setBackgroundResource(R.drawable.edittxt);
calCost.setBackgroundResource(R.drawable.edittxt);
itemText.setBackgroundResource(R.drawable.edittxt);
rTax.setEnabled(true);
rTax.setText("");
rTax.setBackgroundResource(R.drawable.edittxtfocus);
rTax.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
rTax.setEnabled(true);
} else {
rTax.setEnabled(false);
v.setBackgroundResource(R.drawable.edittxt);
}
}
});
}
public void update(){
if (rTax.getText().toString().isEmpty()) {
taxValue = 16.5;
} else if (!rTax.getText().toString().isEmpty()) {
taxValue = Double.parseDouble(rTax.getText().toString());
}
//CHECKS THE TAX VALUE IF IT NEEDS TO BE CONVERTED
if (taxValue > 1) {
taxValue = taxValue / 100;
} else {
taxValue = taxValue * 1;
}
//CUSTOM VALIDATOR FOR QUANTITY FIELD
if (editQuantity.getText().toString().isEmpty()) {
quantity = 1;
} else if (!editQuantity.getText().toString().isEmpty()) {
quantity = Integer.parseInt(editQuantity.getText().toString());
}
if(rb.getText() == "Include Tax"){
newCost = (((cost = Double.parseDouble(editCost.getText().toString())) * taxValue) + cost) * quantity;
calCost.setText(decimalFormat.format(newCost).toString());
}
else if(rb.getText() == "Exclude Tax"){
newCost = ((cost = Double.parseDouble(editCost.getText().toString())) * quantity);
calCost.setText(decimalFormat.format(newCost).toString());
}
trueCost = cost * quantity;
bTotal = trueCost;
aTotal = newCost;
}
}
Move the rgroup.setOnCheckedChangeListener out of the update() method and into the onCreateView(). You should not have to set the listener every time the text has been updated.
The update method called after text entry can probably just update the tax value if a valid value has been entered and either the check boxes have been selected.
Update with another suggestion
I would lookup the radio button by comparing text as you are doing, some time in the future you may want to change the text in the resource file or apply another locale and this code will stop working.
if(rb.getText() == "Include Tax")
I would suggest comparing against the id itself:
if (checkedId == R.id.radio1 )
Another Suggestion:
Consider changing your variable names to lead with a lower case character. Leading with an upper case letter makes it look like either class name or a constant and make the code a bit more difficult to read.
private EditText itemText;
private EditText editCost;
private EditText editQuantity;
private EditText calcost;
private EdtiText rTax;
You can also remove all(some) the focus change listeners you have and set those attributes in the android drawable resources. Take a look here.
Update 9/9/2016 22:22
A bit better, but as you've found out calls to update can throw a null pointer if rb had never been initialized. You should check for a null rb in the update method and give the user a notice to select an option. You could also assign rb to either of the two values from the start in the onCreateView, so it is never null.
You should probably also add a call to update() after setting rb in the radio group callback. This will allow the screen to update as soon as they choose an option.

Validating email does not work with textInputLayout

I have the textInputLayout for which i added the listener. I'm trying to check if the enter email is valid or not. To do this i have written the below code. but it does not work. Even if i give the right email id it shows valid email id.
package com.hari.ga.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.hari.ga.lending.R;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Shiva on 17-10-2015.
*/
public class Personal extends AppCompatActivity {
protected Button next;
EditText editText;
String e;
Boolean check;
protected TextInputLayout emailText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personal_details);
editText = (EditText)findViewById(R.id.email);
next = (Button)findViewById(R.id.next_button);
emailText = (TextInputLayout)findViewById(R.id.emailText);
e = editText.getText().toString();
emailText.getEditText().addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
boolean c = checkEmail(e);
if (!c) {
emailText.setError("valid email id is required");
emailText.setErrorEnabled(true);
} else {
emailText.setErrorEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
/* editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!TextUtils.isEmpty(e)) {
Snackbar.make(v, e, Snackbar.LENGTH_SHORT).show();
emailText.setErrorEnabled(false);
} else {
emailText.setError("Input required");
emailText.setErrorEnabled(true);
}
}
}); */
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(check==false) {
Toast.makeText(getApplicationContext(), "Please make sure the details are right", Toast.LENGTH_LONG).show();
} else{
Intent intent = new Intent(Personal.this, HomeDetails.class);
startActivity(intent);
}
}
});
}
public static boolean checkEmail(String email) {
Pattern EMAIL_ADDRESS_PATTERN = Pattern
.compile("[a-zA-Z0-9+._%-+]{1,256}" + "#"
+ "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" + "(" + "."
+ "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" + ")+");
return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}
}
This should work,
android.util.Patterns.EMAIL_ADDRESS.matcher(emailText.getText().toString()).matches())
The code is not working because you are checking on the String e instance in your TextChangedListener, which you assigned in your onCreate method, which means that you are not checking on the updated text from the EditText. No matter what the changes are to your EditText, it is always checking on that String instance and thus always returning true.
What you need to do is to get the updated text from the EditText and use it to run your check function. You can do it like this
#Override
public void afterTextChanged(Editable s) {
String updatedText = s.toString();
// do your check on updatedText here
}
Try this function...
public boolean isValidEmailAddress(String email) {
String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}
Solved:
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Pattern EMAIL_ADDRESS_PATTERN = Pattern
.compile("[a-zA-Z0-9+._%-+]{1,256}" + "#"
+ "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" + "(" + "."
+ "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" + ")+");
if(!EMAIL_ADDRESS_PATTERN.matcher(s).matches())
{
emailText.setError("valid email id is required");
emailText.setErrorEnabled(true);
} else {
emailText.setErrorEnabled(false);
}
}
Try this one
private boolean validateEmail() {
String email = inputEmail.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(inputEmail);
return false;
} else {
inputLayoutEmail.setErrorEnabled(false);
}
return true;
}

Android Class cast exception with radio group widget?

Building a small quiz application and have some issues with the code, it worked on a previous version but that got delete during a fresh install of windows, when i try open up the a activity for a quiz i keep getting an unexpected error and the log says after a few lines
Java.lang.classexception : android.widget.Radio Group
the code for the activity looks like this
package com.example.quizzards;
import java.io.FileNotFoundException;
import java.util.Arrays;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("NewApi")
public class GamesActivity extends Activity {
boolean rightWrong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_games);
try {
#SuppressWarnings("unused")
Questions questions = new Questions(getApplicationContext());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
update();
Button answer = (Button) findViewById(R.id.AnswerButton);
answer.setOnClickListener(new OnClickListener()
{
public void onClick(View V)
{
RadioGroup allOptions = (RadioGroup) findViewById(R.id.questions);
int toCheck = allOptions.getCheckedRadioButtonId();
if (toCheck == -1) {
Toast.makeText(GamesActivity.this, "Please select an option.",
Toast.LENGTH_SHORT).show();
} else {
RadioButton selected = (RadioButton) findViewById(allOptions
.getCheckedRadioButtonId());
rightWrong = Questions.checkAnswer(selected.getText()
.toString());
if (rightWrong == true) {
Toast.makeText(GamesActivity.this, "Right!!!",
Toast.LENGTH_SHORT).show();
Questions.addPoint();
update();
} else {
Questions.incorrectTry();
int remainingTries = Questions.getRemainingTries();
if (remainingTries == 0) {
// Toast.makeText(MainActivity.this,
// "Your final score is " + Questions.getScore() + ".",
// Toast.LENGTH_SHORT).show();
Intent i = new Intent(GamesActivity.this,
ResultsActivity.class);
startActivity(i);
} else {
Toast.makeText(
GamesActivity.this,
"Wrong!!! " + remainingTries
+ " tries left.",
Toast.LENGTH_SHORT).show();
}
}
allOptions.clearCheck();
}
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(GamesActivity.this, PlayActivity.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.games, menu);
return true;
}
public void update()
{
if (Questions.finished()) {
Intent i = new Intent(GamesActivity.this,
ResultsActivity.class);
startActivity(i);
} else {
String[] aQuestion = Questions.getNextQuestion();
String[] temp = Arrays.copyOfRange(aQuestion, 1, aQuestion.length);
for (int i = 0; i < temp.length; i++) {
int r = (int) (Math.random() * (i + 1));
String swap = temp[r];
temp[r] = temp[i];
temp[i] = swap;
}
TextView textViewQuestion = (TextView) findViewById(R.id.questions);
textViewQuestion.setText(aQuestion[0]);
TextView textViewOption1 = (TextView) findViewById(R.id.option1);
textViewOption1.setText(temp[0]);
TextView textViewOption2 = (TextView) findViewById(R.id.option2);
textViewOption2.setText(temp[1]);
TextView textViewOption3 = (TextView) findViewById(R.id.option3);
textViewOption3.setText(temp[2]);
TextView textViewOption4 = (TextView) findViewById(R.id.option4);
textViewOption4.setText(temp[3]);
TextView runningTotal = (TextView) findViewById(R.id.runningTotal);
runningTotal.setText("Total: " + Questions.getScore());
}
}
}
The XML file contains a radio group and few radio buttons, when i try to run the code without any sort of radio buttons and comment out the code, works perfectly
Make sure all your RadioButtons and RadioGroup have different id's in the layout file.
Another small optimization would be to look for the RadioButtons inside RadioGroup as following.
RadioButton selected = (RadioButton) allOptions.findViewById(
allOptions.getCheckedRadioButtonId());

Categories

Resources