I am creating a coffee ordering app for school. My intent for the code below is to increment or decrement the coffee integer based on whether the subtractCoffeeButton or addCoffeeButton is clicked. coffeeTV is used to show the user the number of coffee's queued to be ordered. subtotal and subtotalTV are used to hold the price and display it to the user.
As it is, the subtractCoffee and addCoffee buttons work to increment coffee and coffeeTV from 0 to 1 and vise-versa, subtotal and subtotalTV also work for displaying 0.00 and 2.5, but it won't increment any further than that. Further button clicks result in nothing happening when it is expected to increment coffee to 2,3,4,etc. and subtotal to 5.00,7.50,10.00,etc.
Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_relative);
Button subtractCoffee = (Button) findViewById(R.id.subtractCoffeeButton);
subtractCoffee.setOnClickListener(this);
Button addCoffee = (Button) findViewById(R.id.addCoffeeButton);
addCoffee.setOnClickListener(this);
}
#Override
public void onClick(View v) {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
String coffeeString = coffeeTV.getText().toString();
int coffeeTracker = Integer.parseInt(coffeeString);
TextView subTotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffeeTracker == 0) {
break;
} else if (coffeeTracker == 1) {
coffee = 0;
coffeeTracker = 0;
coffeeTV.setText(Integer.toString(coffee));
break;
} else {
coffee = coffee - 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal - coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
}
break;
case R.id.addCoffeeButton:
coffee += 1;
coffeeTracker+=1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal + coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
break;
}
}
#Override
public void onClick(View v) {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
These variables have to be outside the onClick method.
Everytime you call onClick they get initiated again with 0.
because
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
are in the local scope of your method. Declare as member variable and their value will persist as long as the current Activity is not destroyed
The problem is that you have
double subtotal = 0.00;
int coffee = 0;
at the beginning of your onClick() function. Thus, every time you click a button, you reset the number to 0 and then increment it to 1.
Besides, I'd recommend you to define separate OnClickListener instead of a global one. Something like:
public class MainActivity extends AppCompatActivity {
AppWidgetManager appWidgetManager;
SharedPreferences preferences;
SharedPreferences.Editor editor;
InputMethodManager inputMethodManager;
EditText mainEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityManager.TaskDescription taskDescription =
new ActivityManager.TaskDescription(null, null, getResources().getColor(R.color.primaryDark));
setTaskDescription(taskDescription);
getWindow().setNavigationBarColor(getResources().getColor(R.color.primary));
}
appWidgetManager = AppWidgetManager.getInstance(this);
inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
String savedText = preferences.getString("mainText", "");
mainEditText = (EditText) findViewById(R.id.mainEditText);
mainEditText.setMovementMethod(new ScrollAndSelectMovingMethod());
mainEditText.getText().append(savedText);
Selection.setSelection(mainEditText.getText(), savedText.length());
mainEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inputMethodManager.showSoftInput(mainEditText, InputMethodManager.SHOW_IMPLICIT);
}
});
mainEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
onEditTextTextChanged(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
#Override
public void onBackPressed() {
finish();
}
private void onEditTextTextChanged(String text) {
saveText(text);
updateWidget();
}
private void saveText(String text) {
editor.putString("mainText", text);
editor.commit();
}
private void updateWidget() {
int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(this, Widget.class));
for (int id : ids)
Widget.updateAppWidget(appWidgetManager, id);
}
}
As already said subtotal, coffe and coffePrice need to be outside of the onClick function. Also coffeTracker should always be the same as coffe as far as I can see, so you dont need the variable
This should be your code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
double subtotal = 0.00;
int coffee = 0;
double coffeePrice = 2.50;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_relative);
Button subtractCoffee = (Button) findViewById(R.id.subtractCoffeeButton);
subtractCoffee.setOnClickListener(this);
Button addCoffee = (Button) findViewById(R.id.addCoffeeButton);
addCoffee.setOnClickListener(this);
}
#Override
public void onClick(View v) {
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
TextView subTotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffee == 0) {
break;
} else if (coffee == 1) {
coffee = 0;
coffeeTV.setText(Integer.toString(coffee));
break;
} else {
coffee = coffee - 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal - coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
}
break;
case R.id.addCoffeeButton:
coffee += 1;
coffeeTV.setText(Integer.toString(coffee));
subtotal = subtotal + coffeePrice;
subTotalTV.setText(Double.toString(subtotal));
break;
}
}
Either you go with the other answers approach (field variables) or you read and parse the amounts on each onClick(). In code it would look something like:
static final double COFFEE_PRICE = 2.50;
#Override
public void onClick(View v) {
TextView coffeeTV = (TextView) findViewById(R.id.tvCoffeeOrder);
String coffeeString = coffeeTV.getText().toString();
int coffee = Integer.parseInt(coffeeString);
TextView subtotalTV = (TextView) findViewById(R.id.tvSubtotalCost);
String subtotalString = subtotalTV.getText().toString();
double subtotal = Double.parseDouble(subtotalString);
switch (v.getId()) {
case R.id.subtractCoffeeButton:
if (coffee == 0) {
break;
}
coffee--;
subtotal -= COFFEE_PRICE;
coffeeTV.setText(Integer.toString(coffee));
subtotalTV.setText(Double.toString(subtotal));
break;
case R.id.addCoffeeButton:
coffee++;
subtotal += COFFEE_PRICE;
coffeeTV.setText(Integer.toString(coffee));
subtotalTV.setText(Double.toString(subtotal));
break;
}
}
Related
I am facing difficulties in showing data in textView after going to the next page
I am storing the return value in EMI variable but I am not able to print that value in the next page textview.
public class EmiCalculator extends AppCompatActivity {
public static double emical(double p,double r, double t)
{
double emi;
r = r / (12 * 100); // one month interest
t = t * 12; // one month period
emi = (p * r * (double)Math.pow(1 + r, t)) / (double)(Math.pow(1 + r, t) - 1);
return (emi);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emi_calculator);
EditText getText_1, getText_2, getText_3;
getText_1 = (EditText) findViewById(R.id.emi_editText_1);
getText_2 = (EditText) findViewById(R.id.emi_editText_2);
getText_3 = (EditText) findViewById(R.id.emi_editText_3);
Button calculateButton = (Button) findViewById(R.id.emi_calculate);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double emi_edit_Text_01 = Double.parseDouble(getText_1.getText().toString());
double emi_edit_Text_02 = Double.parseDouble(getText_2.getText().toString());
double emi_edit_Text_03 = Double.parseDouble(getText_3.getText().toString());
double emi = emical(emi_edit_Text_01, emi_edit_Text_02, emi_edit_Text_03);
String str = String.valueOf(emi);
TextView result = (TextView) findViewById(R.id.result_textView_3);
result.setText(""+emi);
Intent nextPage = new Intent(EmiCalculator.this,Result.class);
startActivity(nextPage);
}
});
}
}
you must use
Intent.putExtra
for send data to another activity.
in first activity:
Intent nextPage = new Intent(EmiCalculator.this,Result.class);
nextPage.putExtra("result",""+emi);
startActivity(nextPage);
in second activity:
Intent intentResult=this.getIntent;
if(intentResult.hasExtra("result")){
textview.setText(intent.getStringExtra("result"));
}
I am new to Android Studio. I have gone through the official developer.android.com training and I decided to create a new and simple app called Grocery+ in which user will enter the price and quantity of particular item and app will display total sum.
I have done all UI based work then today I switched to programming. I am an experienced programmer of Java. I have also done all the work in it but:
1- my app crashes when I try to enter the first .
Then I have to enter any other value first then first value.
2- even after above hack my app doesn't display anything on 'grand total
Plese help :(((
package com.amostrone.akash.grocery;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static int Quantity[] = new int[4];
static float Price[] = new float[4];
public static double total=0;
static TextView txtValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtValue = (TextView) findViewById(R.id.txtExample);
}
/////////// QUANTITY
public void input_Quantity(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity);
calc();
}
public void input_Quantity2(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity2);
Quantity[1] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity3(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity3);
Quantity[2] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity4(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity4);
Quantity[3] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity5(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity5);
Quantity[4] = Integer.parseInt(x.toString());
calc();
}
/////////////// Quantity
////////////// Price
public void input_Price(View view) {
EditText x = (EditText) findViewById(R.id.editPrice);
Price[0] = Float.parseFloat(x.toString());
calc();
}
public void input_Price2(View view) {
EditText x = (EditText) findViewById(R.id.editPrice2);
Price[1] = Float.parseFloat(x.toString());
calc();
}
public void input_Price3(View view) {
EditText x = (EditText) findViewById(R.id.editPrice3);
Price[2] = Float.parseFloat(x.toString());
calc();
}
public void input_Price4(View view) {
EditText x = (EditText) findViewById(R.id.editPrice4);
Price[3] = Float.parseFloat(x.toString());
calc();
}
public void input_Price5(View view) {
EditText x = (EditText) findViewById(R.id.editPrice5);
calc();
}
///////////// Price
/////////////// Calculate
public static void calc()
{
for(int i=0;i<=4;i++)
total += (Quantity[i] * Price[i]);
String str = Double.toString(total);
txtValue.setText(str);
}
////////////// Calculate }
Looking at your code it appears your are triggering EditText value get and calculation on click event (via xml). This does not work this way as they are triggered immediately. One of the approaches to solve this problem is to go the TextWatcher route. Check the below code built around that, I also refactored it a bit (should be lesser prone to memory leaks now):
public double mTotal;
private TextView mTextView;
private EditText[] mQuantityEditTexts = new EditText[5];
private EditText[] mPriceEditTexts = new EditText[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.txtExample);
mQuantityEditTexts[0] = (EditText) findViewById(R.id.editQuantity);
mQuantityEditTexts[1] = (EditText) findViewById(R.id.editQuantity2);
mQuantityEditTexts[2] = (EditText) findViewById(R.id.editQuantity3);
mQuantityEditTexts[3] = (EditText) findViewById(R.id.editQuantity4);
mQuantityEditTexts[4] = (EditText) findViewById(R.id.editQuantity5);
mPriceEditTexts[0] = (EditText) findViewById(R.id.editPrice);
mPriceEditTexts[1] = (EditText) findViewById(R.id.editPrice2);
mPriceEditTexts[2] = (EditText) findViewById(R.id.editPrice3);
mPriceEditTexts[3] = (EditText) findViewById(R.id.editPrice4);
mPriceEditTexts[4] = (EditText) findViewById(R.id.editPrice5);
for (int i = 0; i < 5; i++) {
mQuantityEditTexts[i].addTextChangedListener(mTextWatcher);
mPriceEditTexts[i].addTextChangedListener(mTextWatcher);
}
}
private TextWatcher mTextWatcher = 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) {
calc();
}
#Override
public void afterTextChanged(Editable s) {
}
};
public void calc()
{
try {
for (int i = 0; i <= 4; i++)
mTotal += Integer.parseInt(mQuantityEditTexts[i].getText().toString()) *
Double.parseDouble(mPriceEditTexts[i].getText().toString());
String str = Double.toString(mTotal);
mTextView.setText(str);
} catch (NumberFormatException e) {
Toast.makeText(this, "WTF! Enter valid numbers!", Toast.LENGTH_SHORT).show();
}
}
I have created custom edittext which does not hangs.
SearchTimerEditText
I am trying to display a double from this class in another class..
So here is my code:
public class Calculator extends AppCompatActivity {
Button next;
TextView pPrice;
TextView renovations;
TextView misc2;
TextView util;
TextView rep;
TextView mortage;
TextView misc1;
TextView rent;
public double getStartingCostsResult() {
return startingCostsResult;
}
double startingCostsResult;
double monthlyMinus;
double monthlyPlus;
double monthlyROI;
double yearlyROI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
// Setting these textviews to those in the xml.
pPrice = (TextView) findViewById(R.id.pPrice);
renovations = (TextView) findViewById(R.id.renovations);
misc2 = (TextView) findViewById(R.id.misc2);
util = (TextView) findViewById(R.id.util);
rep = (TextView) findViewById(R.id.rep);
mortage = (TextView) findViewById(R.id.mortage);
misc1 = (TextView) findViewById(R.id.misc);
rent = (TextView) findViewById(R.id.rent);
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent expense = new Intent(getApplicationContext(), Results.class);
if ((pPrice.getText().length() > 0) && (renovations.getText().length() > 0) && (misc2.getText().length() > 0)) {
double price = Double.parseDouble(pPrice.getText().toString());
// double costs = Double.parseDouble(cCosts.getText().toString());
double reno = Double.parseDouble(renovations.getText().toString());
double misc = Double.parseDouble(misc2.getText().toString());
startingCostsResult = price + reno + misc;
if((util.getText().length()>0) && (rep.getText().length()>0) && (mortage.getText().length()>0) && (misc1.getText().length()>0)){
double utilities = Double.parseDouble(util.getText().toString());
double repairs = Double.parseDouble(rep.getText().toString());
double mort = Double.parseDouble(mortage.getText().toString());
double miscsell = Double.parseDouble(misc1.getText().toString());
monthlyMinus = utilities + repairs + mort + miscsell;
if (rent.getText().length()>0){
double monthlyRent = Double.parseDouble(rent.getText().toString());
monthlyPlus = monthlyRent;
monthlyROI = monthlyPlus - monthlyMinus;
yearlyROI = monthlyROI *12;
startActivity(expense);
}else{
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
So I am trying to display the yearlyROI double in another class.
I have tried this:
Calculator calc = new Calculator();
otherClass.setText((int) calc.yearlyROI);
But my app crashes when I click next.
you should put an extra in the expense intent like this.
expense.putExtra("yearlyRoi",yearlyRoi);
then in the nexet activity you can get it like this.
Intent recievedIntent = this.getIntent();
double yearlyRoi = recievedIntent.getDoubleExtra("yearlyRoi", defaultValue);
default value can be 0.0 or anything you want.
as for the crash i think its another problem,you need to give us error log of your app.
If you want to access variables from a different Activity you need to add them to your intent.
In your case:
expense.putExtra("yearlyROI", yearlyROI);
startActivity(expense);
Then in your new Activity:
double yearlyROI = getIntent().getDoubleExtra("yearlyROI");
Hope it helps!
I have 2 EditText fields set up for numeric inputs, a button to start a calculation on the 2 inputs when pressed, and a TextView to display the result of the calculation. For repeated calculations I want to clear the TextView result as soon as either EditText is changed.
Following the reply to "A better way to OnClick for EditText fields" given by 'avalancha', my program clears the result when the first EditText field is changed, but retains the previous answer if only the second EditText field is changed. Yet I have used the same source code for both fields.
Can someone explain why, and how to cure this? my code is appended:
public class DoublesActivity extends ActionBarActivity {
private EditText textBox1, textBox2;
private Button calcButton;
private Context context;
#Override
protected void onCreate(Bundle outState) {
super.onCreate(outState);
setContentView(R.layout.activity_doubles); // Sets the layout .xml file
context = this.getApplicationContext();
textBox1 = (EditText) findViewById(R.id.editText1); //textBox1 holds a reference to the editText1 object in the xml layout
textBox2 = (EditText) findViewById(R.id.editText2);
textBox1.setText("");
textBox2.setText("");
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
textBox2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v2, boolean hasFocus2) {
if (hasFocus2) {
textBox3.setText("");
}
}
});
textBox1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v1, boolean hasFocus1) {
if (hasFocus1) {
textBox3.setText("");
}
}
});
calcButton = (Button) findViewById(R.id.button1);
calcButton.setBackgroundColor(Color.CYAN);
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CharSequence userNumber1 = textBox1.getText(); //userNumber1 is a CharSequence holding the text in textBox1
CharSequence userNumber2 = textBox2.getText();
Float handicap1 = Float.parseFloat(userNumber1.toString()); //convert to integer
Float handicap2 = Float.parseFloat(userNumber2.toString()); //convert to integer
Float handicapT = calculate(handicap1, handicap2);
CharSequence userNumber = String.valueOf(handicapT);
if (handicapT > 98.5) {
userNumber = "Non-valid h'cap 1!";
}
if (handicapT < -98.5) {
userNumber = "Non-valid h'cap 2!";
}
textBox3.setText(userNumber); // put result in the TextView
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userNumber = textBox3.getText();
outState.putCharSequence("savedText", userNumber);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userText = savedInstanceState.getCharSequence("savedText");
textBox3.setText(userText);
}
Float calculate(Float h1, Float h2) {
float[] handicapArray;
handicapArray = new float[29];
handicapArray[0] = 28;
handicapArray[1] = 26;
handicapArray[2] = 24;
handicapArray[3] = 22;
handicapArray[4] = 20;
handicapArray[5] = 18;
handicapArray[6] = 16;
handicapArray[7] = 14;
handicapArray[8] = 12;
handicapArray[9] = 11;
handicapArray[10] = 10;
handicapArray[11] = 9;
handicapArray[12] = 8;
handicapArray[13] = 7;
handicapArray[14] = 6;
handicapArray[15] = 5;
handicapArray[16] = 4.5F;
handicapArray[17] = 4;
handicapArray[18] = 3.5F;
handicapArray[19] = 3;
handicapArray[20] = 2.5F;
handicapArray[21] = 2;
handicapArray[22] = 1.5F;
handicapArray[23] = 1;
handicapArray[24] = 0.5F;
handicapArray[25] = 0;
handicapArray[26] = -0.5F;
handicapArray[27] = -1;
handicapArray[28] = -1.5F;
int index1 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h1 - handicapArray[i]) < 0.001) {
index1 = i;
break;
}
}
if (index1 == -1) {
EditText textBox1 = (EditText) findViewById(R.id.editText1);
textBox1.setText("");
}
int index2 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h2 - handicapArray[i]) < 0.001) {
index2 = i;
break;
}
}
if (index2 == -1) {
EditText textBox2 = (EditText) findViewById(R.id.editText2);
textBox2.setText("");
}
int indexT = (index1 + index2) / 2; // Correctly rounds indexT halves down.
Float result = handicapArray[indexT];
if (index1 == -1) {
result = 99F;
}
;
if (index2 == -1) {
result = -99F;
}
;
return result;
}
Use addTextChangedListener to clear textview.
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
resultTextView.setText("");
}
});
For example please use below link
android on Text Change Listener
I am trying to save and store data in an android app using java. At the moment the data will not save and it causes my app to crash. Can anyone make any suggestions to my code? Part of my page includes a total budget and I am difficulty storing and saving the total budget.
public class Summary extends Activity implements TextWatcher, View.OnClickListener
{
DecimalFormat df = new DecimalFormat("£0.00");
int noOfGifts, giftsPurchased;
double cost;
EditText budgetEntered;
double savedBudget = 0;
String budgetString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
budgetEntered = (EditText) findViewById(R.id.s2TotalBudget);
budgetEntered.addTextChangedListener(this);
Button saveBudget = (Button) findViewById(R.id.s2ViewList);
saveBudget.setOnClickListener(saveButtonListener);
if(savedBudget != 0)
{
saveBudget.setText(budgetString);
}
Bundle passedInfo = getIntent().getExtras();
if (passedInfo != null)
{
cost = passedInfo.getDouble("cost");
noOfGifts = passedInfo.getInt("noOfGifts");
giftsPurchased = passedInfo.getInt("giftsPurchased");
}
Button logoutButton = (Button) findViewById(R.id.s2LogoutButton);
logoutButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, MainActivity.class);
startActivity(myIntent);
}
});
Button viewList = (Button) findViewById(R.id.s2ViewList);
viewList.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, GiftList.class);
startActivity(myIntent);
}
});
String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")},
{"Number of Presents bought:", (giftsPurchased + "")},
{"Cost: £", (cost + "")},
{"Budget: £", "50"}};
String passedBudget=null;
//convert totalPresents to double from String
String tempPresents = summary[0][1];
int presents = Integer.parseInt(tempPresents);
//convert presentsBought to double from String
String tempBought = summary[1][1];
int presentsToBuy = Integer.parseInt(tempBought);
//Number of presents
TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult);
s2PresentResult.setText(summary[0][1]);
//Number of presents to buy
TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult);
s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + "");
Bundle passedId = getIntent().getExtras();
if (passedId != null)
{
passedBudget = passedId.getString("Enter Budget");
}
//EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget);
//s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this);
//s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE);
//Number of people
//TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget);
//s2TotalBudget.setText("Enter budget");
//Number of people
TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost);
s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1])));
//Output if over or under budget
TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget);
//convert totalCost to double from String
String temp = summary[2][1];
double totalCost = Double.parseDouble(temp);
//convert totalBudget to double from String
String tempTwo = "14";
double totalBudget = Double.parseDouble(tempTwo);
if((totalCost>totalBudget)&&(totalBudget!=0))
{
s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0));
s2CalculateOverBudget.setText("You are over budget");
}
else if(totalBudget==0){
s2CalculateOverBudget.setText("");
}
else {
s2CalculateOverBudget.setText("You are within budget");
}
}
public View.OnClickListener saveButtonListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(budgetEntered.getText().length()>0)
{
budgetString = budgetEntered.getText().toString();
}
}
};
public void onClick(View v)
{
}
#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)
{
this it the best way to store and load value in Android:
save values: (put this where you want to save the values, for example in the onStop or onPause method. Or, in your case, in the onClick method)
SharedPreferences settings = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("testValue", value);
editor.commit();
load values:
SharedPreferences settings = getSharedPreferences("MyPref", 0);
value = settings.getInt("testValue", defValue);