Numerous errors on one line of code? - android

I am nearly complete with my first android app, which is a basic tip calculator. I am having trouble with line 36
amountDisplayTextView = (TextView) findViewById(R.id.amountDisplayTextView);
I am getting these errors:
Multiple markers at this line
-Syntax error, insert ";" to complete FieldDeclaration
-Syntax error on token ".", ... expected
-Syntax error on token "amountDisplayTextView", VariableDeclaratorId expected after this token
-Return type for the method is missing
-Syntax error on token ")", { expected after this token
-Syntax error on token "amountDisplayTextView", VariableDeclaratorId expected after this token
I have tried to trouble shoot, but I hit a wall. Any assistance is appreciated! Here is the rest of the class.
package com.example.tipcalc;
import java.text.NumberFormat;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextWatcher;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity {
//currency and percent formatters
private static final NumberFormat currencyFormat =
NumberFormat.getCurrencyInstance();
private static final NumberFormat percentFormat =
NumberFormat.getPercentInstance();
private double billAmount = 0.0; //bill amount entered by the user
private double customPercent = 0.18; //initial custom percent value
private TextView amountDisplayTextView; //shows formatted bill amount
private TextView percentCustomTextView;//shows custom tip percentage
private TextView tip15TextView; // shows 15% tip
private TextView total15TextView; // shows total with 15% tip
private TextView tipCustomTextView; // shows custom tip amount
private TextView totalCustomTextView; //shows total with custom tip
//called when activity is first created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //call superclass's version
setContentView(R.layout.activity_main); //inflate GUI
}
//get references to the TextViews
//that MainActivity interacts with programmatically
amountDisplayTextView = (TextView) findViewById(R.id.amountDisplayTextView);
percentCustomTextView = (TextView) findViewById(R.id.percentCustomTextView);
tip15TextView = (TextView) findViewById(R.id.tip15TextView);
total15TextView = (TextView) findViewById(R.id.total15TextView);
tipCustomTextView = (TextView) findViewById(R.id.tipCustomTextView);
totalCustomTextView = (TextView) findViewById(R.id.totalCustomTextView);
}
//update 15% textviews
private void updateStandard()
{
//calculate 15% tip and total
double fifteenPercentTip = billAmount * 0.15;
double fifteenPercentTotal = billAmount + fifteenPercentTip;
//display 15% tip and total formatted as currency
tip15TextView.setText(currencyFormat.format(fifteenPercentTip));
total15TextView.setText(currencyFormat.format(fifteenPercentTotal));
} //end method updateStandard
//updates the custom tip and total TextViews
private void updateCustom()
{
//show customPercent in percentCustomTextView formatted as %
percentCustomTextView.setText(percentFormat.format(customPercent));
//calculate the custom tip and total
double customTip = billAmount * customPercent;
double customTotal = billAmount + customTip;
//display custom tip and total formatted as currency
tipCustomTextView.setText(currencyFormat.format(customTip));
totalCustomTextView.setText(currencyFormat.format(customTotal));
}//end updateCustom
//called when the user changes the position of SeekBar
private OnSeekBarChangeListener customSeekBarListener =
new OnSeekBarChangeListener()
{
//update customPercent, then call updateCustom
#Override
publicvoid onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
//set customPercent to position of the SeekBar's thumb
customPercent = progress / 100.0; //update the custom tip TextViews
updateCustom(); //update the custom tip TextView's
}; //end method onProgressChanged
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}// end method onStartTrackingTouch
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}// end method onStopTrackingTouch
};//end OnSeekBarChangeListener
//event-handling object that responds to amountEditText's events
private TextWatcher amountEditTextWatcher = new TextWatcher()
{
//called when the user enters a number
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
//convert amountEditText's text to a double
try
{
billAmount = Double.parseDouble(s.toString()) / 100.0;
} //end try
catch (NumberFormatException e)
{
billAmount = 0.0; //default if an exception occurs
}//end catch
//display currency formatted bill amount
amountDisplayTextView.setText(currencyFormat.format(billAmount));
updateStandard(); //update the 15% tip Textviews
updateCustom(); //update the custom tip TextViews
}; //end method onTextChanged
#Override
public void afterTextChanged(Editable s)
{
}//end method afterTextChanged
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after)
{
} // end method before TextChanged
}; //end amountEditTextWatcher
}//end mainActivity class

its all about your {}{} your declaring your variables at class level and trying to instantiate them too if you instantiate them inside of onCreate where they should be it will work
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //call superclass's version
setContentView(R.layout.activity_main); //inflate GUI
//get references to the TextViews
//that MainActivity interacts with programmatically
amountDisplayTextView = (TextView) findViewById(R.id.amountDisplayTextView);
percentCustomTextView = (TextView) findViewById(R.id.percentCustomTextView);
tip15TextView = (TextView) findViewById(R.id.tip15TextView);
total15TextView = (TextView) findViewById(R.id.total15TextView);
tipCustomTextView = (TextView) findViewById(R.id.tipCustomTextView);
totalCustomTextView = (TextView) findViewById(R.id.totalCustomTextView);
}

Related

Substraction between Float

Please guys help me! I'm going crazy ! Below is a brief summary of my code that should be used to make a simple subtraction . Should I just read the amount of SCONTRINO and if you put CONTANTI , the field VINCITE , will have as setText SCONTRINO - CONTANTI , same with VINCITE , will CONTANTI.setText SCONTRINO - VINCITE .
But despite everything seems to be well written , when I insert a field , I StackOverflowError by the two Update methods.
public class AssegnaScontoActivity extends Activity {
TextView contanti;
TextView vincite;
TextView scontrino;
Float contantiFloat;
Float vinciteFloat;
Float scontrinoFloat;
public void onCreate(Bundle savedInstanceState) {
//INIZIALIZZAZIONE ACTIVITTY
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.assegna_sconto_activity_landscape);
//--------------------------
contantiFloat = Float.parseFloat(contanti.getText().toString());
vinciteFloat = Float.parseFloat(vincite.getText().toString());
scontrinoFloat = Float.parseFloat(1000);
contanti = (TextView) findViewById(R.id.contanti);
vincite = (TextView) findViewById(R.id.importo_vincite);
scontrino = (TextView) findViewById(R.id.importo_scontrino);
contanti.addTextChangedListener(new TextChangedListener()
{
#Override
public void numberEntered(Float number)
{
contantiFloat = number;
updateVincite();
}
});
vincite.addTextChangedListener(new TextChangedListener()
{
#Override
public void numberEntered(Float number)
{
vinciteFloat = number;
updateContanti();
}
});
}
private void updateVincite()
{
Float total = scontrinoFloat - contantiFloat; // This is where you apply your function
vincite.setText(""+total); // need to do that otherwise int will
// be treated as res id.
}
private void updateContanti()
{
Float total = scontrinoFloat - vinciteFloat; // This is where you apply your function
contanti.setText(""+total); // need to do that otherwise int will
// be treated as res id.
}
private abstract class TextChangedListener implements TextWatcher
{
public abstract void numberEntered(Float number);
#Override
public void afterTextChanged(Editable s)
{
String text = s.toString();
try
{
Float parsedFloat = Float.parseFloat(text);
numberEntered(parsedFloat);
} catch (NumberFormatException e)
{
Log.w(getPackageName(), "Non si puo' parsare '" + text + "' col numero", e);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
}
Your code is going into an infinite loop because you are changing the text when afterTextChanged() is called, which causes afterTextChanged() to be called again and so on until eventually you overflow your call stack.
You can stop this by only setting the text inside updateVincite() and updateContanti() if it is different to the current text.
e.g.:
private void updateVincite()
{
Float total = scontrinoFloat - contantiFloat; // This is where you apply your function
String text = ""+total;
if(!vincite.getText().toString().contentEquals(text))
vincite.setText(text); // need to do that otherwise int will
// be treated as res id.
}
and do the same for updateContanti()
First define contanti and vincite .
Change code as follows.
contanti = (TextView) findViewById(R.id.contanti);
vincite = (TextView) findViewById(R.id.importo_vincite);
scontrino = (TextView) findViewById(R.id.importo_scontrino);
contantiFloat = Float.parseFloat(contanti.getText().toString());
vinciteFloat = Float.parseFloat(vincite.getText().toString());
scontrinoFloat = Float.parseFloat(1000);

Calculation goes wrong when I started using SeekBar

public class Main extends Activity implements OnClickListener {
TextView ePrice;
TextView InputPrice;
TextView InputPercent;
TextView ePercent;
private SeekBar volumeControl = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
/** Remove title bar */
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Hide Auto Keyboard */
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
/** Hide Auto Keyboard End here */
InputPrice = (TextView) findViewById(R.id.ePrice);
InputPercent = (TextView) findViewById(R.id.ePercents);
ePrice = (TextView) findViewById(R.id.ePrice);
ePercent = (TextView) findViewById(R.id.ePercents);
Here is my SeekBar. Before this SeekBar I have been using EditText and every thing was ok but after i started using this SeekBar the SECOND result is so weird!!
SeekBarPer = (SeekBar) findViewById(R.id.volume_bar);
SeekBarPer.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
progressChanged = progress;
TextView label = (TextView) findViewById(R.id.ePercents);
label.setText(""+progressChanged);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
what I have:
One EditText up One TextView under the SeekBar and Two another TextView are down to show the result of calculating the Price and the Percent! The First result is going well but the second is NOT!
For example if i calculate 30 dollars minus 50% i got the first result 15 and the second one 35.
What I want:
Just to correct the second result
Here is the Calculation:
// show the price to get
final TextView tR = (TextView) findViewById(R.id.viewResult);
// show the price to pay
final TextView tRpay = (TextView) findViewById(R.id.viewResultPay);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
double price = Double.parseDouble(ePrice.getText().toString());
double percent = Double.parseDouble(ePercent.getText().toString());
double pri = (price / 100.0f) * percent;;
double per = percent * ((100.0f - price)/100.0f);
tR.setText(String.valueOf(pri));
tRpay.setText(String.valueOf(per));
tR.setText("" + pri);
tRpay.setText("" + per);
// catch
} catch (NumberFormatException ex) {
// write a message to users
tR.setText("");
}
}
});
}
Update:
I am using the SeekBar as a percent. So when I move the SeekBar there will be numbers 0-100 in the second TextView.
Thanks in advance!
This should be what you want:
DiscountValue = price*discount/100.0f;
ValueToPay = price - DiscountValue;

How do I create an android application that takes in numbers in pairs, multiplies them, and adds the result?

Until three weeks ago I knew nothing about developing applications for android, and with very basic Java background.
However, I took up the interest, and I'm now tying to develop a simple application that performs basic arithmetic operations.
What I would like the application to do is take in figures input by the user, up to 20 pairs, multiply each pair separately, and then add the results.
I have gotten through the multiplication of the pairs, but can't get onto adding up the results.
This is what I have so far for the multiplication part, and it works okay....
public class CalcAlgorithm extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
final String LOG_TAG = "MainScreen";
super.onCreate(savedInstanceState);
setContentView(R.layout.calc_algorithm);
final EditText value1=(EditText) findViewById(R.id.value1);
final EditText value2=(EditText) findViewById(R.id.value2);
final EditText value3=(EditText) findViewById(R.id.value3);
final EditText value4=(EditText) findViewById(R.id.value4);
final EditText value5=(EditText) findViewById(R.id.value5);
final EditText value6=(EditText) findViewById(R.id.value6);
final EditText value7=(EditText) findViewById(R.id.value7);
final EditText value8=(EditText) findViewById(R.id.value8);
final EditText value9=(EditText) findViewById(R.id.value9);
final EditText value10=(EditText) findViewById(R.id.value10);
final TextView result=(Button) findViewById (R.id.multiplyValues);
final TextView result2=(Button) findViewById (R.id.multiplyValues2);
final TextView result3=(Button) findViewById (R.id.multiplyValues3);
final TextView result4=(Button) findViewById (R.id.multiplyValues4);
final TextView result5=(Button) findViewById (R.id.multiplyValues5);
final TextView result6=(Button) findViewById (R.id.addButton);
Button multiplyButton = (Button)findViewById(R.id.multiplyValues);
multiplyButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
try {
int val1=Integer.parseInt(value1.getText().toString());
int val2=Integer.parseInt(value2.getText().toString());
Integer answer = val1*val2;
result.setText(answer.toString());
} catch (Exception e) {
Log.e(LOG_TAG, "Failed to multiply numbers",e);
}
}
});
Button multiplyButton2 = (Button) findViewById(R.id.multiplyValues2);
multiplyButton2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val3 = Integer.parseInt(value3.getText().toString());
int val4 = Integer.parseInt(value4.getText().toString());
Integer answer = val3 * val4;
result2.setText(answer.toString());
} catch (Exception e) {
Log.e(LOG_TAG, "Failed to multiply numbers",e);
}
}
});
Button multiplyButton3 = (Button) findViewById(R.id.multiplyValues3);
multiplyButton3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val5 = Integer.parseInt(value5.getText().toString());
int val6 = Integer.parseInt(value6.getText().toString());
Integer answer = val5 * val6;
result3.setText(answer.toString());
} catch (Exception e) { Log.e(LOG_TAG, "Failed to multiply numbers",e);}}
});
Button multiplyButton4 = (Button) findViewById(R.id.multiplyValues4);
multiplyButton4.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val7 = Integer.parseInt(value7.getText().toString());
int val8 = Integer.parseInt(value8.getText().toString());
Integer answer = val7 * val8;
result4.setText(answer.toString());
} catch (Exception e) { Log.e(LOG_TAG, "Failed to multiply numbers",e);}}
});
Button multiplyButton5 = (Button) findViewById(R.id.multiplyValues5);
multiplyButton5.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
int val9 = Integer.parseInt(value9.getText().toString());
int val10 = Integer.parseInt(value10.getText().toString());
Integer answer = val9 * val10;
result5.setText(answer.toString());
} catch (Exception e) {
Log.e(LOG_TAG,"Failed to multiply number",e);
}
}
});
Is this the right path? And, i realize that there is a way of summarising the code into fewer lines and not as i have it. Could someone please show me how I can go about having fewer lines of code, and then adding up the results all at once?
After adding the values, I'd again like to perform some more (basic) operations on the results, but i think after I have known how to add the results, I should be able to figure my way from there.
**Perhaps i should point out that i would require the addition to be done once separately i.e on clicking of an added button (TotalSum,maybe) separately and not progressively as the multiplication goes on, such that the user can see the multiplied results for each pair of figures entered, and the total of all paired results on clicking a separate button..
It would also be of immense help if i could get links to some books/documentation/videos that could help with arithmetic functions in writing android applications.
Any help will be greatly appreciated guys. :)
You could add a calculateResultSum() method, which you call at the end of each onClick method with does something like
void calculateResultSum() {
Integer res1 = Integer.parse(result.getText.toString());
// .. get all the other results
Integer finalResult = res1 + res2 + res2 + res4 + res5;
//do something with the result
}
BUT your approach is very redundant, i.e. you have the same code in all of you onClick methods. This is considered bad code style, you should try to extract the actual processing of the numbers into one single method and call this method from each of the listeners, for example
void addNumbers(TextView tv1, TextView tv2, TextViev res){
try {
Integer val1=Integer.parseInt(value1.getText().toString());
Integer val2=Integer.parseInt(value2.getText().toString());
Integer answer = val1*val2;
res.setText(answer.toString());
} catch (Exception e) { Log.e(LOG_TAG, "Failed to multiply numbers",e);}}
}
and set the onClicks to
multiplyButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
addNumbers(value1,value2,result);
calculateResultSum();
});
with the corresponding views for each Button. Hope I could help.
If I understood correctly, here is the solution.
Create a class variable like private int total=0; and in each setOnClickListener add your answers to this variable.
Integer answer = val1*val2;
total += answer;
Also instead of using 5 Button and 10 TextViews you can do this with simply one Button and one TextView storing results in another TextView but you said you are practicing, if it is just to practice it should be alright.
package com.example.calc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num1_edt=(EditText)findViewById(R.id.num1_edt);
final EditText num2_edt=(EditText)findViewById(R.id.num2_edt);
final Button add_btn=(Button)findViewById(R.id.add_btn);
findViewById(R.id.sub_btn);
findViewById(R.id.mul_btn);
findViewById(R.id.div_btn);
add_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int a=Integer.parseInt(num1_edt.getText().toString());
int b=Integer.parseInt(num2_edt.getText().toString());
Integer n=a*b;
Toast.makeText(getApplicationContext(),"Your Num Is:"+n.toString(),Toast.LENGTH_LONG).show();
}
});
}
}

Infinite loop when button is clicked on Android

What I'm trying to do is:
If the EditText input is equal to the random number generated, then stop the loop otherwise keep on the loop and reset input text.
For some reason, I'm getting an infinite loop. I am new to programming, any help is really appreciated.
Here is the code:
public class Main extends Activity implements OnClickListener{
private TextView tvResult;
private TextView tvRandTest;
private EditText et1;
private String randonNumber;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvResult = (TextView) findViewById(R.id.textView4);
tvRandTest = (TextView) findViewById(R.id.textView3);
et1 = (EditText) findViewById(R.id.editText1);
}//End Main
public void myClickHandler(View view)
{
if(view.getId() == R.id.button1)
{
//Generates 6 one digit Random Numbers
int randonNumber1 = (int) (0 + Math.random() * 9);
//Parse Numbers
String rd1 = Integer.toString(randonNumber1);
randonNumber = rd1;
boolean done = false;
do
{
et1.getText().toString();
if(et1.equals(randonNumber))
{
Toast.makeText(Main.this,"Equal Number", Toast.LENGTH_SHORT).show();
tvResult.setText(randonNumber);
done = true;
}//end if
else
{
Toast.makeText(Main.this,"Not Equal Number", Toast.LENGTH_SHORT).show();
et1.setText("");
}//end else
}//End While
while(!done);
}//End if
if(view.getId() == R.id.button2)
{
tvRandTest.setText(randonNumber);
}
}//End Method
#Override
public void onClick(View arg0) {
// TODO
}
}//End Class
if(et1.equals(randonNumber))
I will change it with
if(et1.equals(String.valueOf(randonNumber)))
you put directly the int value inside the equals method two things will happen:
the autboxing will create an Integer object starting from the int value
the toString() method will be called through this object.
the toString() method of Integer in android, as the doc stands:
Returns a string containing a concise, human-readable description of this object.
So you are compareing the address of the new object with the content of et1 and not with its real value. Here the reference
In this line et1.getText().toString(); you need to assign result to variable, for example String input = et1.getText().toString(); Then in next line you need to compare two strings, if(input.equals(randonNumber)) But your program can hang cause of infinity loop on UI thread. You should use TextWatcher
to handle when text in EditText was changed

updating the wrong textedit field

Could you guys lend me some fresh eyes and tell me what where I should look to find the missing link? I am trying to do a mortgage calculation by pulling value from purchasePrice, downPayment, and interestRate EditText fields to do the calculation. I tested the updateStandand() by setting the TextEdit field to interest rate. However, when I run the app in AVD, if I type a purchase price, the monthly payment field would reflect the price. If i move down to interest rate field and type in a number, the monthly payment field would change to the value of the interest rate.
Thank you!
package com.example.mortgagecalc;
import com.example.mortgagecalc.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.text.Editable;
public class Main extends Activity {
private static final String PURCHASE_AMOUNT = "PURCHASE_AMOUNT";
private static final String CUSTOM_LENGTH = "CUSTOM_LENGTH";
private static final String DOWN_PAYMENT = "DOWN_PAYMENT";
private static final String INTEREST_RATE = "INTEREST_RATE";
private int currentPurchaseAmount; //purchase amount entered by user
private int currentCustomLength; //length of loan set with SeekBar
private int currentDownPayment; //down payment entered by user
private double currentInterestRate; //interest rate entered by user
private EditText purchaseAmountEditText; //accepts user input for purchase amount
private EditText downPaymentEditText; //accepts user input for down payment amount
private EditText interestRateEditText; //accepts user input for interest rate
private EditText tenYearEditText; //display monthly payment for 10yr. loan
private EditText twentyYearEditText; //display monthly payment for 20yr. loan
private EditText thirtyYearEditText; //display monthly payment for 30yr. loan
private EditText customMonthlyEditText; //display monthly payment for custom length
private TextView customLengthTextView; //display custom loan length
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//check if app just started or being restored from memory
if (savedInstanceState == null) //app just started running
{
currentPurchaseAmount = 0; //initialize to zero
currentCustomLength = 10; //initialize custom loan length to 10
currentDownPayment = 0; //initialize to zero
currentInterestRate = 0.0; //initialize to zero
}
else
{
currentPurchaseAmount = savedInstanceState.getInt(PURCHASE_AMOUNT);
currentCustomLength = savedInstanceState.getInt(CUSTOM_LENGTH);
currentDownPayment = savedInstanceState.getInt(DOWN_PAYMENT);
currentInterestRate = savedInstanceState.getDouble(INTEREST_RATE);
}
purchaseAmountEditText = (EditText) findViewById(R.id.purchaseAmountEditText);
downPaymentEditText = (EditText) findViewById(R.id.downPaymentEditText);
interestRateEditText = (EditText) findViewById(R.id.interestRateEditText);
tenYearEditText = (EditText) findViewById(R.id.tenYearEditText);
twentyYearEditText = (EditText) findViewById(R.id.twentyYearEditText);
thirtyYearEditText = (EditText) findViewById(R.id.thirtyYearEditText);
customMonthlyEditText = (EditText) findViewById(R.id.customMonthlyEditText);
customLengthTextView = (TextView) findViewById(R.id.customMonthlyTextView);
purchaseAmountEditText.addTextChangedListener(textWatcher);
downPaymentEditText.addTextChangedListener(textWatcher);
interestRateEditText.addTextChangedListener(textWatcher);
SeekBar customSeekBar = (SeekBar) findViewById(R.id.customSeekBar);
customSeekBar.setOnSeekBarChangeListener(customSeekBarListener);
}
private void updateStandard(){
double interestRate = currentInterestRate;
//double loanPrinciple = currentPurchaseAmount - currentDownPayment;
//double tenYearMonthlyPayment = loanPrinciple;
tenYearEditText.setText(String.valueOf(interestRate));
}
private void updateCustom(){
//customLengthTextView.setText(currentCustomLength + "year");
double customInterestRate = ((currentInterestRate/12) * .01);
int customLoanPrinciple = currentPurchaseAmount - currentDownPayment;
double customMonthlyPayment = customLoanPrinciple * customInterestRate /
(1-Math.pow(1+customInterestRate, -(currentCustomLength*12)));
customMonthlyEditText.setText(Double.toString(customMonthlyPayment));
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putDouble(PURCHASE_AMOUNT, currentPurchaseAmount);
outState.putDouble(DOWN_PAYMENT, currentDownPayment);
outState.putDouble(INTEREST_RATE, currentInterestRate);
outState.putDouble(CUSTOM_LENGTH, currentCustomLength);
}
private OnSeekBarChangeListener customSeekBarListener = new OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
currentCustomLength = seekBar.getProgress();
updateCustom();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
};
private TextWatcher textWatcher = new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
try
{
currentPurchaseAmount = Integer.parseInt(s.toString());
currentDownPayment = Integer.parseInt(s.toString());
currentInterestRate = Integer.parseInt(s.toString());
}
catch(NumberFormatException e)
{
currentPurchaseAmount = 0;
currentDownPayment = 0;
currentInterestRate = 0.0;
}
updateStandard();
updateCustom();
}
#Override
public void afterTextChanged(Editable s)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You're using a single TextWatcher for all three fields, and updating all three fields in the onTextChanged method.
I'm guessing that what you really want is three separate TextWatcher instances - one for each field, and to update only that one value in each one.

Categories

Resources