Cannot clear a TextView since I added a TextWatcher? - java

I have a simple golf scorecard app I'm developing. I have 9 textviews for now in which you enter a score hole by hole. When the score is entered the TextView background goes green if below par, red if above and white if even. IU have done this with TextWatchers.
I have a clear all Fields class, which clears all the textviews which always worked. But since I added the textwatchers for the scores my clear all textViews has stopped working. The program crashes.
This is my clear all TextView Code,
public class clearButtonListner implements OnClickListener {
private Activity activity;
public clearButtonListner(Activity activity){
this.activity = activity;
}
#Override
public void onClick(View v) {
TextView et1 = (TextView)this.activity.findViewById(R.id.EditTextScore1);
TextView et2 = (TextView)this.activity.findViewById(R.id.EditTextScore2);
TextView et3 = (TextView)this.activity.findViewById(R.id.EditTextScore3);
TextView et4 = (TextView)this.activity.findViewById(R.id.EditTextScore4);
TextView et5 = (TextView)this.activity.findViewById(R.id.EditTextScore5);
TextView et6 = (TextView)this.activity.findViewById(R.id.EditTextScore6);
TextView et7 = (TextView)this.activity.findViewById(R.id.EditTextScore7);
TextView et8 = (TextView)this.activity.findViewById(R.id.EditTextScore8);
TextView et9 = (TextView)this.activity.findViewById(R.id.EditTextScore9);
TextView ettotal = (TextView)this.activity.findViewById(R.id.editTextTotalScore);
et1.setText("");
et2.setText("");
et3.setText("");
et4.setText("");
et5.setText("");
et6.setText("");
et7.setText("");
et8.setText("");
et9.setText("");
ettotal.setText("");
}
}
Example of one of my textWatchers,
public class textWatcher1 implements TextWatcher{
private Activity activity;
public textWatcher1(Activity activity){
this.activity = activity;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
int p1 = 5;
// Create my TextViews
TextView et1 = (TextView)this.activity.findViewById(R.id.EditTextScore1);
int s1 = (int)(Integer.parseInt(et1.getText().toString()));
if(s1 < p1){
et1.setBackgroundColor(Color.GREEN);
}
else if(s1 > p1){
et1.setBackgroundColor(Color.RED);
}
else if(s1 == p1){
et1.setBackgroundColor(Color.WHITE);
}
}
}
Any help would be great. The app crashes with throw new NumberFormatException("Invalid int: \"" + s + "\""); Exception.

That is because after erasing all your EditTexts with that Button click, your afterTextChanged(Editable s) callback is called. It is expecting a some content on your EditText but finds nothing, thus throwing that Exception, in parseInt().
You just have to add a condition for that code to execute, this is, only if the length of the text is bigger that 0. That way you will prevent the callback from making your app crash after clearing the EditTexts.
So, just add this line inside afterTextChanged(Editable s):
if(s.length()>0){
//your existing code
}
I advise you to only fill those EditTexts with content that is convertible to a number, or you will get that Exception again.

Related

toggle.setchecked inside a onTextChanged event

I'm trying to use a togglebutton to display the status of a number check when the number is entered in a textbox. I've already set it up with a TextView and that works fine but I'd like to replace it graphically. No errors are thrown up with the following but the state doesn't change with the .SetChanged events in the OnChanged event:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ToggleButton togShortCircuit = (ToggleButton) findViewById(R.id.togShortCircuit);
togShortCircuit.setClickable(false);
final EditText txtOCVListen = (EditText) findViewById(R.id.txtOCV);
txtOCVListen.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
txtOCVListen.setFilters(new InputFilter[]{new CustomRangeInputFilter(0f, 16.0f)});
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(txtOCVListen.getText().toString().equals(null) || txtOCVListen.getText().toString().equals("")){
fltOCV = 0;
} else {
fltOCV = Float.parseFloat(txtOCVListen.getText().toString());
}
//Short Circuit
if (fltOCV < 10.6 && fltULV > 0 && fltULV <= 8.5) {
TextView lblShortCircuitStatus = (TextView) findViewById(R.id.lblShortCircuitStatus);
lblShortCircuitStatus.setText("True");
lblShortCircuitStatus.setTextColor(0xFFD51817); //Red
togShortCircuit.setChecked(true);
} else {
TextView lblShortCircuitStatus = (TextView) findViewById(R.id.lblShortCircuitStatus);
lblShortCircuitStatus.setText("False");
lblShortCircuitStatus.setTextColor(0xFF808080); //Grey
togShortCircuit.setChecked(false);
}
Can't seem to figure out how to declare togShortCircuit to have it recognized with the event. Using Android Studio 3.12 and developing for Android 7.0.

Dynamic calculation of a TextView that is linked to a seris of buttons

I'm trying to create this flow on an application I'm building. I am having a little bit of trouble getting the TextView to be friendly with any kind of formula/conditions. Any suggestions on how I can get the TextView to output the result dynamically through my text watchers? Thanks in advance!
Text Views
//------------------DISPLAY-----------------\\
netsale = (TextView)findViewById(R.id.netsale_input);
//--------------WAIT ASSISTANT--------------\\
waMain = (TextView)findViewById(R.id.txt_wa_main);
waSplit = (TextView)findViewById(R.id.txt_wa_split);
Clear Button
public void clr_Clicked(View sender){
netsale.setText("0");
isempty=true;
}
Number Pad
static boolean isempty=true;
public void num_Clicked(View sender){
Button bt=(Button)sender;
if(netsale.getText().length()>5)return;
if(isempty)
{
if(bt.getText().toString().equals("0"))return;
netsale.setText(bt.getText());
isempty=false;
}
else
{
netsale.append(bt.getText());
}
}
Text Watchers
private TextWatcher filterTextWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
}
When you click on a button, lets say "7", you should append that value to the TextView by utilizing setText(CharSequence);
So at first if your TextView is blank (""), when you click the 7, it should result in your TextView showing "7"

Get the user input from edittext and as soon the input is correct change textview (Android)

I have two text views and a EditText. In the TextViews are integers they are random generated. I want when the entry is correct in editText (Without OK button) the two textview change to new random integers.
I already have:
Random random1 = new Random(); int rand = random1.nextInt(100);
Random random2 = new Random();
int rand1 = random2.nextInt(100);
final TextView textview1 = (TextView)findViewById(R.id.textView1);
textview1.setText(String.valueOf(rand));
final TextView textview2 = (TextView)findViewById(R.id.textView2);
textview1.setText(String.valueOf (rand1));
final EditText edittext = (EditText)findViewById(R.id.editText1);
int f = -1; // or other invalid value
if (edittext.getText().toString().length() > 0) {
f = Integer.parseInt(edittext.getText().toString());
}
int answer = rand1 + rand;
if (f == answer) {
textview1.setText(rand++);
textview2.setText(rand1++);
}else {
System.out.println("!");
}
Thanks for your Help!
you can use the following block of code to check if the data in edit text has been set to correct value and now textview should be updated
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
yourEditText = (EditText) findViewById(R.id.yourEditTextId);
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
yourEditText. ...
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
}
}

How to use TextWatcher to automatically get values from edittext and multiply them?

The app force shuts when i enter a number in edittext. I want the app to automatically calculate the BMI when values are entered without pressing on a button.
I know nothing about TextWatcher yet i researched and came up with this code. Its not working though. Whats wrong with it?
public class BodyMassIndex extends Activity implements View.OnClickListener,
TextWatcher {
double result;
EditText age, height, weight;
ToggleButton sex, cmin, kglb;
TextView tvResult;
double heightInt = 1;
double weightInt = 0;
int ageInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
initialize();
sex.setOnClickListener(this);
cmin.setOnClickListener(this);
kglb.setOnClickListener(this);
}
private void initialize() {
// TODO Auto-generated method stub
age = (EditText) findViewById(R.id.etAge);
height = (EditText) findViewById(R.id.etHeight);
weight = (EditText) findViewById(R.id.etWeight);
sex = (ToggleButton) findViewById(R.id.tbSex);
cmin = (ToggleButton) findViewById(R.id.tbCMIN);
kglb = (ToggleButton) findViewById(R.id.tbKGLB);
tvResult = (TextView) findViewById(R.id.tvResult);
age.addTextChangedListener(this);
height.addTextChangedListener(this);
weight.addTextChangedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.tbCMIN:
heightInt = heightInt * 0.0254;
break;
case R.id.tbKGLB:
weightInt = weightInt * 0.45359237;
break;
}
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
calculate();
}
private void calculate() {
// TODO Auto-generated method stub
Editable H = height.getText(), W = weight.getText();
if(H != null)
heightInt = Double.parseDouble(H.toString());
if (W != null)
weightInt = Double.parseDouble(W.toString());
result = weightInt / (heightInt * heightInt);
String textResult = "Your BMI is " + result;
tvResult.setText(textResult);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
'
From http://developer.android.com/reference/android/text/TextWatcher.html about afterTextChanged method: "but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively....you can use setSpan(Object, int, int, int) in onTextChanged(CharSequence, int, int, int) "
you already have :
height = (EditText) findViewById(R.id.etHeight);
weight = (EditText) findViewById(R.id.etWeight);
only change calculate() method:
private void calculate()
{
//remove the Editable thing declaration...
heightInt = Double.parseDouble(height.getText().toString());
wightInt = Double.parseDouble(weight.getText().toString());
result = weightInt / (heightInt * heightInt);
String textResult = "Your BMI is " + result;
tvResult.setText(textResult);
}
P.S: Here we're assuming that EditText contains only a number and not letters. Letters will force close the app. So you'll have to check for that.

On Edittext Automatic calculation

Currently I am using my onEditTextchanger. To format my currency. What I am wondering if it is possible to call and run the Calculate function from my main java whenever the user types in the edittext field .
I would like it to work similar the the javascript function onkeyup="calc(this.form)"
Since I am not sure how to implement this. Any ideas would be appreciated. Once Again Thanks in advance for your help.
class
public class CurrencyTextWatcher implements TextWatcher {
boolean mEditing;
public CurrencyTextWatcher() {
mEditing = false;
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(!mEditing) {
mEditing = true;
String digits = s.toString().replaceAll("\\D", "");
NumberFormat nf = NumberFormat.getCurrencyInstance();
try{
String formatted = nf.format(Double.parseDouble(digits)/100);
s.replace(0, s.length(), formatted);
} catch (NumberFormatException nfe) {
s.clear();
}
mEditing = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
Java
public class CalcTestActivity extends Activity {
private EditText txta;
private EditText txtb;
private TextView txtc;
private TextView txtd;
private double a = 0;
private double b = 0;
private double c = 0;
private double d = 0;
private Button buttonCalc;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
txta.addTextChangedListener(new CurrencyTextWatcher());
txtb.addTextChangedListener(new CurrencyTextWatcher());
}
private void initControls() {
txta = (EditText)findViewById(R.id.txta);
txtb = (EditText)findViewById(R.id.txtb);
txtc = (TextView)findViewById(R.id.txtc);
txtd = (TextView)findViewById(R.id.txtd);
buttonCalc = (Button)findViewById(R.id.buttonCalc);
buttonCalc.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {calculate(); }});}
private void calculate() {
//textViewResult.setText(addNumbers());
a=Double.parseDouble(txta.getText().toString().replace("$", "").replace(",", ""));
b=Double.parseDouble(txtb.getText().toString().replace("$", "").replace(",", ""));
c=Math.round(a*.88);
txtc.setText(GlobalMoney.FormatValue(c));
d=Math.round((a*.87)+(b*.61)*(c*.25));
txtd.setText(GlobalMoney.FormatValue(d));
}
}
You can call it right in afterTextChanged(), is there any problem you bump into when doing so?

Categories

Resources