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!
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 have 5 EditTexts, when I am clicking on the button, I want to check that all of them are not empty in order to take data from them and put it into the database, and start another activity. If all of them are empty, a message would be displayed that "You need to fill everything". However, when all EditTexts are empty and I press the button, application crashes. How can I solve this problem and what can I do to get the desired result? (The code is not ended yet.)
public class Main2Activity extends AppCompatActivity {
DatabaseHelper myDB;
Button btnAdd;
EditText editText1,editText2,editText3,editText4,editText5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
editText1 = (EditText) findViewById(R.id.name);
editText2 = (EditText) findViewById(R.id.year);
editText3 = (EditText) findViewById(R.id.month);
editText4 = (EditText) findViewById(R.id.day);
editText5 = (EditText) findViewById(R.id.price);
btnAdd = (Button) findViewById(R.id.btn_add);
myDB = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name1 = editText1.getText().toString();
String year2 = editText2.getText().toString();
int year1 = Integer.parseInt(year2);
String month2 = editText3.getText().toString();
int month1 = Integer.parseInt(month2);
String day2 = editText4.getText().toString();
int day1 = Integer.parseInt(day2);
String price2 = editText5.getText().toString();
int price1 = Integer.parseInt(price2);
if (name1.length() != 0 && year2.length() != 0 && month2.length() != 0 && day2.length() != 0 && price2.length() != 0) {
AddData(name1, year1, month1, day1, price1);
editText1.setText("");
editText2.setText("");
editText3.setText("");
editText4.setText("");
editText5.setText("");
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(Main2Activity.this, "You need to fill everything", Toast.LENGTH_LONG).show();
}
}
});
}
public void AddData(String name1, int year1, int month1, int day1, int price1) {
boolean insertData = myDB.addData(name1,year1,month1,day1,price1);
if(insertData==true){
Toast.makeText(this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
}
}
}
The crash happens here:
int year1 = Integer.parseInt(year2);
When EditText is empty, you are passing an empty string to Integer.parseInt, which results in NumberFormatException. To avoid this, move the parsing code into the validation block.
#Override
public void onClick(View v) {
String name1 = editText1.getText().toString();
String year2 = editText2.getText().toString();
String month2 = editText3.getText().toString();
String day2 = editText4.getText().toString();
String price2 = editText5.getText().toString();
if (name1.length() != 0 && year2.length() != 0 && month2.length() != 0 && day2.length() != 0 && price2.length() != 0) {
// Move parsing code here
int year1 = Integer.parseInt(year2);
int month1 = Integer.parseInt(month2);
int day1 = Integer.parseInt(day2);
int price1 = Integer.parseInt(price2);
AddData(name1, year1, month1, day1, price1);
editText1.setText("");
editText2.setText("");
editText3.setText("");
editText4.setText("");
editText5.setText("");
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(Main2Activity.this, "You need to fill everything", Toast.LENGTH_LONG).show();
}
}
You can allow the user to press the button only after entering text to all of your editTexts like this:
if (all editTexts got text inside) {
//not all editTexts got text inside them, user cant press the button
button.setClickable(false);
}
else{
//all editTexts got text inside them, user can now press the button
button.setClickable(true);
}
Note - "all editTexts got text inside" that I wrote inside the if statment is for you to make in any way that you would like to check.
I'm struggling to create a very simple app. There are Product Names with matching Product Numbers. User enters a Number and the corresponding Name appears.
editTextField1 = the number user types
button1 = the search button
editTextField2 = the product name appears
Now my code is working but there is only one problem, when the user doesn't enter anything and clicks on button1 the app crashes. So I need some sort of exception handler maybe? Im struggling to get my head around it. I know how I'm coding, by declaring loads of variables, is long-winded lol.
public class MainActivity extends AppCompatActivity {
private Button button1;
private EditText editText1;
private EditText editText2;
private int a = 123;
private String b = "TV";
private int c = 333;
private String d = "Radio";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
double pNumber = Double.parseDouble(editText1.getText().toString());
if(pNumber == a){
editText2.setText(b);
}
else if (pNumber == c){
editText2.setText(d);
}
else
editText2.setText("Invalid Product Number");
}
};
button1.setOnClickListener(myOnClickListener);
In Addition to Spartas Answer, it would also be a good idea to check for a valid Double input:
try {
double pNumber = Double.parseDouble(text);
catch(NumberFormatException e){
//Do ExceptionHandling
}
Use this:
View.OnClickListener myOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editText1.getText().toString();
if(!TextUtils.isEmpty(text)) {
// EditText1 is not empty
try {
double pNumber = Double.parseDouble(text);
if(pNumber == a)
editText2.setText(b);
else if (pNumber == c){
editText2.setText(d);
else
editText2.setText("Invalid Product Number");
}
catch(NumberFormatException e) {
// Invalid input, not a double
editText2.setText("Invalid double input");
}
}
else {
// EditText1 is empty
editText2.setText("EditText1 is empty");
}
}
};
There are basically 2 ways how you can handle this
1) Use try - catch
try{
double pNumber = Double.parseDouble(editText1.getText().toString());
}catch(NumberFormatException e){
//show a message to user
}
2) Use input sanitation
String number = editText1.getText().toString();
boolean isNumber = number.matches("^-?\\d+$"));//haven't tried this though
if(!isNumber) //if not number
//show a message to user
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;
}
}
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);