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.
Related
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;
}
}
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.
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.
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;
}
package com.andineagoe.gradienttermic;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PressureAltimeterActivity extends Activity implements SensorEventListener {
private PressureAltimeterActivity this_activity_;
protected Sensor sensor_pressure_;
protected SensorManager sensor_manager_;
protected double slp_inHg_;
protected double pressure_hPa_;
protected KalmanFilter pressure_hPa_filter_;
protected double last_measurement_time_;
private static final double SLT_K = 288.15;
private static final double TLAPSE_K_PER_M = -0.0065;
private static final double G_M_PER_S_PER_S = 9.80665;
private static final double R_J_PER_KG_PER_K = 287.052;
private static final double PA_PER_INHG = 3386;
private static final double FT_PER_M = 3.2808399;
private static final double KF_VAR_ACCEL = 0.0075;
private static final double KF_VAR_MEASUREMENT = 0.05;
Here I try to add my button and textviews and it works
**Button mButton = (Button) findViewById(R.id.saveButton);
TextView mPressure = (TextView) findViewById(R.id.pressureValue);
TextView mTemperature = (TextView) findViewById(R.id.tempValue);
TextView mLogSave = (TextView) findViewById(R.id.logSave);
Now I get 3-4 error when I try to set the onClick Listener
Multiple markers at this line
- Syntax error on token "setOnClickListener", = expected after
this token
- Syntax error on token(s), misplaced construct(s)
The method onClick(View) of type PressureAltimeterActivity must override or implement a supertype method
Syntax error, insert "}" to complete ClassBody
mButton.setOnClickListener(new View.onClickListner(){
#Override
public void onClick(View v){
//do stuff
});
public void saveData (){
}**
I just want to modify some log each time I press the button and I can't seem to do so
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pressure_hPa_filter_ = new KalmanFilter(KF_VAR_ACCEL);
setContentView(R.layout.main);
sensor_manager_ = (SensorManager) getSystemService(SENSOR_SERVICE);
sensor_pressure_ = sensor_manager_.getDefaultSensor(Sensor.TYPE_PRESSURE);
}
#Override
public void onResume() {
super.onResume();
this_activity_ = this;
if (slp_inHg_ < 28.1 || slp_inHg_ > 31.0) slp_inHg_ = 29.92;
pressure_hPa_ = 1013.0912;
pressure_hPa_filter_.reset(pressure_hPa_);
last_measurement_time_ = SystemClock.elapsedRealtime() / 1000.;
if (sensor_pressure_ != null) {
sensor_manager_.registerListener(this, sensor_pressure_, SensorManager.SENSOR_DELAY_GAME);
}
}
#Override
public void onPause() {
super.onPause();
sensor_manager_.unregisterListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
}
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putDouble("slp_inHg", slp_inHg_);
}
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
slp_inHg_ = bundle.getDouble("slp_inHg");
}
public boolean onKeyDown(int key_code, KeyEvent key_event) {
if (key_code != KeyEvent.KEYCODE_VOLUME_UP &&
key_code != KeyEvent.KEYCODE_VOLUME_DOWN) return false;
long slp_inHg_long = Math.round(100.0 * slp_inHg_);
if (key_code == KeyEvent.KEYCODE_VOLUME_UP) {
if (slp_inHg_long < 4031) ++slp_inHg_long;
} else if (key_code == KeyEvent.KEYCODE_VOLUME_DOWN) {
if (slp_inHg_long > 2028) --slp_inHg_long;
}
slp_inHg_ = slp_inHg_long / 100.0;
return true;
}
public boolean onKeyUp(int key_code, KeyEvent key_event) {
return key_code == KeyEvent.KEYCODE_VOLUME_UP ||
key_code == KeyEvent.KEYCODE_VOLUME_DOWN;
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_PRESSURE) return; // Should not occur.
pressure_hPa_ = event.values[0];
final double curr_measurement_time = SystemClock.elapsedRealtime() / 1000.;
final double dt = curr_measurement_time - last_measurement_time_;
pressure_hPa_filter_.update(pressure_hPa_, KF_VAR_MEASUREMENT, dt);
last_measurement_time_ = curr_measurement_time;
double inaltime = (long)hPaToFeet(slp_inHg_, pressure_hPa_filter_.getXAbs());
TextView textView = (TextView) findViewById(R.id.pressureValue);
textView.setText("" + inaltime);
}
private static double hPaToFeet(double slp_inHg, double pressure_hPa) {
double factor_m = SLT_K / TLAPSE_K_PER_M;
double exponent = -TLAPSE_K_PER_M * R_J_PER_KG_PER_K / G_M_PER_S_PER_S;
double current_sea_level_pressure_Pa = slp_inHg * PA_PER_INHG;
double altitude_m =
factor_m *
(Math.pow(100.0 * pressure_hPa / current_sea_level_pressure_Pa, exponent) - 1.0);
return /**FT_PER_M* */ altitude_m;
}
}
Try to implement OnClickListener to your class and the method onClick,
public class LoginActivity extends Activity implements OnClickListener {
//...
#Override
public void onClick(View view) {
switch (view.getId()) {
case mButton.getId():
//implement action
break;
default:
break;
}
}
}