If statements forcing program to crash - java

I have asked a few questions before, however I have decided to go back to basics.
I am creating a maths android application, each page has three TextFields that the user can input a number into, I have parsed these TextFields into a double. However, say a user inputs a number into 2 of the TextFields, I would like the program to tell me the value of the third Text field.
At the moment I can get the program to run one calculation, however when I add the if statements in for the remaining two TextFields, the program crashes when I click calculate.
The Key behind the program is to discover which TextField is empty, so that the program can do the correct calculation.
I am currently trying .getText().toString().isEmpty(), but this is not working, I have also tried .length() == 0, however this is not working either.
When I run the emulator and click the calculator button, the program crashes when I add more variables in, however it is fine with just one calculation.
Can anyone help me figure out why the If statements are not working, and if possible can anyone offer a solution?
Sorry if my formatting is off, I'm relatively new to Java, below is the Java
Button calc1 = (Button) findViewById(R.id.current_calculate);
calc1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText Charge1 = (EditText) findViewById(R.id.number_input_2);
EditText Time1 = (EditText) findViewById(R.id.number_input_3);
EditText current1 = (EditText) findViewById(R.id.number_input_1);
TextView Distances_answer = (TextView) findViewById(R.id.Distances_answer);
double charge = Double
.parseDouble(Charge1.getText().toString());
double time = Double.parseDouble(Time1.getText().toString());
double current = Double.parseDouble(current1.getText()
.toString());
// Time is a class in Java
if (current1.getText().toString().isEmpty()) {
Distances_answer.setText("" + charge * time);
} else if (Time1.length() == 0) {
Distances_answer.setText(" " + charge / current);
}
}
});
I have also supplied the XML in case it is needed
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background1"
android:gravity="fill"
android:orientation="vertical"
android:textColor="#ffffff"
tools:context=".CurrentPage" >
<TextView
android:id="#+id/Current_hint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_marginTop="33dp"
android:text="Welcome to the Current Calculation page.
Hint - Use the check boxes to find the values that are missing "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/Equation_letter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/current_calculate"
android:layout_marginTop="37dp"
android:layout_toLeftOf="#+id/current_calculate"
android:text=" HELLO "
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/Distances_answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Equation_letter"
android:layout_alignBottom="#+id/Equation_letter"
android:layout_alignLeft="#+id/current_calculate"
android:layout_alignParentRight="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<TextView
android:id="#+id/t"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Q"
android:layout_alignRight="#+id/Q"
android:layout_below="#+id/Q"
android:layout_marginTop="36dp"
android:gravity="right|top"
android:text="t ="
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<CheckBox
android:id="#+id/custom3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/t"
android:layout_alignLeft="#+id/custom2"
android:background="#drawable/check_box_new"
android:button="#drawable/check_box_new" />
<CheckBox
android:id="#+id/custom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/number_input_3"
android:layout_alignLeft="#+id/custom3"
android:background="#drawable/check_box_new"
android:button="#drawable/check_box_new" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Current_hint"
android:layout_alignRight="#+id/Current_hint"
android:layout_below="#+id/Equation_letter"
android:layout_marginTop="25dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/CurrentmainHelp"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1.31"
android:text="HELP! This equation can be used to calculate the current of an object in amps. The correct equation to discover amps is I=Q/t. Where I = current, Q = charge flowing past a point in the circuit, and t = time taken for the charge to flow. Please note, Q is measure in coulombs and t is measured in seconds, with I being measured in amperes.
Still need more help? "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="18sp"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/Yes_Please"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="36dp"
android:layout_weight="1.31"
android:onClick="CurrentHelp"
android:text="Yes Please"
android:textColor="#ffffff" />
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/current_calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/Calculate_Current"
android:textColor="#ffffff" />
<EditText
android:id="#+id/number_input_2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_above="#+id/t"
android:layout_alignLeft="#+id/number_input_1"
android:layout_alignRight="#+id/number_input_1"
android:ems="10"
android:focusable="true"
android:inputType="numberDecimal"
android:textColor="#ffffff" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/number_input_3"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/t"
android:layout_alignLeft="#+id/number_input_2"
android:layout_alignRight="#+id/number_input_2"
android:ems="10"
android:focusable="true"
android:inputType="numberDecimal"
android:textColor="#ffffff" />
<CheckBox
android:id="#+id/custom2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/number_input_1"
android:layout_marginLeft="45dp"
android:layout_toRightOf="#+id/number_input_1"
android:background="#drawable/check_box_new"
android:button="#drawable/check_box_new" />
<EditText
android:id="#+id/number_input_1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_above="#+id/Q"
android:layout_alignRight="#+id/current_calculate"
android:ems="10"
android:focusable="true"
android:inputType="numberDecimal"
android:singleLine="true"
android:textColor="#ffffff" />
<TextView
android:id="#+id/Q"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Equation_letter"
android:layout_below="#+id/I"
android:layout_marginTop="36dp"
android:gravity="right|top"
android:text="Q ="
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/I"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Q"
android:layout_alignRight="#+id/Q"
android:layout_below="#+id/Current_hint"
android:layout_marginTop="65dp"
android:gravity="right|top"
android:text="I ="
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />

I believe the application crashes because you are parsing the contents of your EditText to doubles even though they may be empty. The Double.parseDouble function will throw a NumberFormatException if it cannot parse a double out of the given String. To fix this, perform a check for empty string before trying to parse, or catch the exception.
For example:
double charge = 0.0; // some default value
if (!Charge1.getText().toString().isEmpty()) {
charge = Double.parseDouble(Charge1.getText().toString());
}
double time = 0.0; // some default value
if (!Time1.getText().toString().isEmpty()) {
time = Double.parseDouble(Time1.getText().toString());
}
double current = 0.0; // some default value
if (!current1.getText().toString().isEmpty()) {
current = Double.parseDouble(current1.getText().toString());
}

Related

How to Display a variable from Mainactivity in a second Activity's Texview

Im a little stuck, how can i get a variable from main activity to be displayed on a second activity?
a code example would be great.
Also a second Problem:
How can i create a function in mainactivty when a button is pressed in a second activity?
This is what i have so far, but when i press the button in the second activity, the app crashes.
the button's function needs to be able to change a variable's value in MainActivity and Run a toast saying it was selected.
Main Activity
//SETTING THE DRINK SIZE BASED ON POPUP BUTTONS
public int DrinkSize;
public void SetDrinkSize_Small(View view) {
DrinkSize = 1;
Toast Small = Toast.makeText(getApplicationContext(),
"Drink Size Set To Small",
Toast.LENGTH_SHORT);
Small.show();
}
public void SetDrinkSize_Medium(View view) {
DrinkSize = 2;
Toast Medium = Toast.makeText(getApplicationContext(),
"Drink Size Set To Medium",
Toast.LENGTH_SHORT);
Medium.show();
}
public void SetDrinkSize_Large(View view) {
DrinkSize = 3;
Toast Large = Toast.makeText(getApplicationContext(),
"Drink Size Set To Large",
Toast.LENGTH_SHORT);
Large.show();
}
CustomPopUp.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="120dp"
android:layout_weight="1"
android:background="#color/Orange"
android:gravity="center_horizontal"
android:orientation="vertical"
android:onClick="SetDrinkSize_Small">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small"
android:textColor="#color/White"
android:textSize="18dp"
android:textStyle="bold" />
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginTop="15dp"
android:src="#drawable/drop" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="120dp"
android:layout_weight="1"
android:background="#color/Green"
android:gravity="center_horizontal"
android:orientation="vertical"
android:onClick="SetDrinkSize_Medium">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium"
android:textColor="#color/White"
android:textSize="18dp"
android:textStyle="bold" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="15dp"
android:src="#drawable/drop" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="120dp"
android:layout_weight="1"
android:background="#color/Orange"
android:gravity="center_horizontal"
android:orientation="vertical"
android:onClick="SetDrinkSize_Large">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large"
android:textColor="#color/White"
android:textSize="18dp"
android:textStyle="bold" />
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginTop="15dp"
android:src="#drawable/drop" />
</LinearLayout>
You can easily send and receive data using intents, as you can see in this Android tutorial: Intent tutorial.
And in case you want to send some data back to the first one, you can use this post: Sending info back.

How can I make better custom dialogs?

I'm creating a game and in it I use a lot of dialogs. The dialogs make up the main menu in a more simple setup then making up an entire activity for it. These dialogs though, they have a grey outline which is really annoying, and in addition when going from one dialog to another, it shrinks down and blows up as one dissapears and another one reappears.
How can I remove the outline and make the transition more smooth? If it is not possible with dialogs, what can an alternative be? I am using custom layouts connected to Java classes that extend Dialog
EDIT
Java:
public class MenuDialog extends Dialog implements View.OnClickListener {
Context con;
Clicker c;
public MenuDialog(Context c, Clicker game) {
super(c);
this.con = c;
this.c = game;
Window window = this.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
show();
}
Button stat, gem, cash, shop, powerup, settings;
#Override
protected void onCreate(Bundle sis){
super.onCreate(sis);
setContentView(R.layout.menu);
setButtons();
}
private void setButtons(){
stat = (Button) findViewById(R.id.bStats);
gem = (Button) findViewById(R.id.bGems);
gem.setOnClickListener(this);
stat.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bStats:
StatDialog sd = new StatDialog(con,c);
sd.show();
break;
case R.id.bGems:
IAPDialog iapd = new IAPDialog(con, c);
iapd.show();
break;
//other buttons
}
dismiss();
}
}
XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
android:id="#+id/relativeLayout"
android:gravity="center_horizontal"
android:background="#drawable/phone_like_bc"
android:orientation="horizontal">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:id="#+id/linearLayout5"
android:layout_marginTop="51dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bStats"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/bGems"
android:background="#drawable/stat_button"
android:layout_toStartOf="#+id/bGems" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/stats"
android:id="#+id/textView17"
android:layout_below="#+id/bStats"
android:layout_alignLeft="#+id/bStats"
android:layout_alignStart="#+id/bStats" />
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/bShop"
android:background="#drawable/shop"
android:layout_below="#+id/textView17" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/shop"
android:textAlignment="center"
android:id="#+id/textView18"
android:layout_alignTop="#+id/textView16"
android:layout_alignLeft="#+id/bShop"
android:layout_alignStart="#+id/bShop" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:id="#+id/linearLayout"
android:layout_marginTop="51dp"
>
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#drawable/gem"
android:id="#+id/bGems"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/linearLayout5"
android:layout_toEndOf="#+id/linearLayout5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/gems"
android:id="#+id/textView15"
android:layout_alignBaseline="#+id/textView20"
android:layout_alignBottom="#+id/textView20"
android:layout_toLeftOf="#+id/bPowerUp"
android:layout_toStartOf="#+id/bPowerUp"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/bPowerUp"
android:background="#drawable/lightning"
android:layout_alignTop="#+id/linearLayout"
android:layout_toLeftOf="#+id/bSettings"
android:layout_toStartOf="#+id/bSettings" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/powerups"
android:id="#+id/textView16"
android:layout_alignBaseline="#+id/bSettings"
android:layout_alignBottom="#+id/bSettings"
android:layout_toLeftOf="#+id/bSettings"
android:layout_toStartOf="#+id/bSettings" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="51dp"
android:gravity="center">
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/bCash"
android:background="#drawable/cash"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text=" " />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/cash"
android:id="#+id/textView19"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/bSettings"
android:background="#drawable/settings"
android:layout_below="#+id/bCash"
android:layout_alignLeft="#+id/bCash"
android:layout_alignStart="#+id/bCash" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/settings"
android:id="#+id/textView20"
android:layout_alignBottom="#+id/bCash"
android:layout_alignLeft="#+id/textView19"
android:layout_alignStart="#+id/textView19" />
</LinearLayout>
</LinearLayout>
There are two more dialog classes both XML and java. I added those two to show that I already know how to add the classes, but I need to know how to remove the outline of the dialog and I need to know how I can smoothen the transition between two dialogs. They have the same background too.
You can use DialogFragments instead of Dialogs, they works as Fragments and you can customize them. Read more about the use of Dialog fragments at https://developer.android.com/reference/android/app/DialogFragment.html
You have a lot of Tutorials to create your own DialogFragments in Google if you don't like the Android Documentation.

Android TextViews not Updating With New Text in onCreate Method of Activity

I am adding TextViews to a simple application, running some code to determine what text should show in each one, then displaying it based on what a user previously entered in a bundle.
The problem is no text is showing up at all!
I am running code in the onCreate method that determines what text should show based on passed in values from a previous activity in a bundle. The values seem to pass in without an error and the other Textviews in the activity reflect the changes, but not the income, expenses or incomeExpenses TextView.
Here is my code:
package androidbro.costoflivingcalculator;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.io.*;
import java.io.Console;
public class FinalGrade extends ActionBarActivity {
//Grade and message strings
public String myGrade;
public String finalMessage;
//Doubles for calculated values
public double rentMortgage;
public double utilities;
public double insurance;
public double phoneInternet;
public double food;
public double carPayment;
public double misc;
public double myIncome;
public double totalExpenses;
public double expensesToIncome;
//Calculate grade based on expenses to income ratio
public String getGrade(double expensesToIncome) {
String grade = "A";
if (expensesToIncome<=0.3) {
grade = "A";
} else if (expensesToIncome<=0.4){
grade = "B";
} else if (expensesToIncome<=0.6) {
grade = "C";
} else if (expensesToIncome<=0.8) {
grade = "D";
} else {
grade = "F";
}
return grade;
}
//Determine final message
public String getFinalMessage(String grade){
String finalMessage;
if (grade == "A"){
finalMessage = "You are living well within your means! You could probably afford to spend more. Either way, great work!";
} else if(grade == "B"){
finalMessage = "You are doing great! Your expenses are well below your income. There are a few areas to improve, but good work!";
} else if(grade == "C") {
finalMessage = "Not too bad, but not great either. You might be in trouble if you lost your income. Try to improve a little!";
} else if(grade == "D") {
finalMessage = "Uh oh! You are spending well over half the money you earn! Consider saving and investing more or it could be trouble.";
} else {
finalMessage = "Oh no! You are spending almost all your income! Save a little and live within your means or else you'll be broke!";
}
return finalMessage;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_grade);
//Income, expenses and bundles
Bundle b = getIntent().getExtras();
rentMortgage = b.getDouble("rentmortgage");
utilities = b.getDouble("utilities");
insurance = b.getDouble("insurance");
phoneInternet = b.getDouble("car");
food = b.getDouble("phone");
carPayment = b.getDouble("food");
misc = b.getDouble("misc");
myIncome = b.getDouble("myincome");
totalExpenses = rentMortgage+utilities+insurance+phoneInternet+food+carPayment+misc;
expensesToIncome = totalExpenses/myIncome;
//Set final message and grade values
myGrade = getGrade(expensesToIncome);
finalMessage = getFinalMessage(myGrade);
//TextViews for setting values
TextView gradeView = (TextView)findViewById(R.id.gradeView);
TextView messageView = (TextView)findViewById(R.id.messageView);
TextView income = (TextView)findViewById(R.id.income);
TextView expenses = (TextView)findViewById(R.id.expenses);
TextView incomeExpenses = (TextView)findViewById(R.id.incomeExpenses);
//Display final grade and message
gradeView.setText(myGrade);
messageView.setText(finalMessage);
income.setText(Double.toString(myIncome));
expenses.setText(Double.toString(totalExpenses));
incomeExpenses.setText(Double.toString(expensesToIncome));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_final_grade, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Display expenses, income and expenses to income percentage on final grade
}
And here is my XML:
<ScrollView
android:layout_width="fill_parent"
android:id="#+id/scrollView"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="ericleeconklin.costoflivingcalculator.FinalGrade">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Grade:"
android:id="#+id/textView2"
android:textSize="40dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="A"
android:id="#+id/gradeView"
android:textSize="85dp"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="You are living well within your means! You could probably afford to spend more. Either way, great work!"
android:id="#+id/messageView"
android:layout_below="#+id/gradeView"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Monthly Income:"
android:id="#+id/yourIncome"
android:layout_below="#+id/messageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:paddingTop="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/income"
android:paddingTop="20dp"
android:background="#ff77ff75"
android:width="180dp"
android:height="25dp"
android:layout_alignBottom="#+id/yourIncome"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="sdsdfsd"
android:textColor="#color/abc_background_cache_hint_selector_material_dark"
android:textIsSelectable="true"
android:textSize="23dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Expenses:"
android:id="#+id/yourExpenses"
android:paddingTop="20dp"
android:layout_below="#+id/income"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/yourIncome"
android:layout_alignEnd="#+id/yourIncome"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/incomeExpenses"
android:paddingTop="20dp"
android:background="#ff77ff75"
android:width="180dp"
android:height="25dp"
android:layout_alignBottom="#+id/textView4"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/expenses"
android:paddingTop="20dp"
android:background="#ff77ff75"
android:width="180dp"
android:height="25dp"
android:layout_alignBottom="#+id/yourExpenses"
android:layout_alignLeft="#+id/incomeExpenses"
android:layout_alignStart="#+id/incomeExpenses"
android:text="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Expenses/Income"
android:id="#+id/textView4"
android:paddingTop="20dp"
android:layout_below="#+id/yourExpenses"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/incomeExpenses"
android:layout_toStartOf="#+id/incomeExpenses"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Here are some tips:"
android:id="#+id/textView5"
android:paddingTop="350dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
</ScrollView>
Instead of this:
income.setText(Double.toString(myIncome));
expenses.setText(Double.toString(totalExpenses));
incomeExpenses.setText(Double.toString(expensesToIncome));
Do this:
income.setText(String.valueOf(myIncome);
expenses.setText(String.valueOf(totalExpenses));
incomeExpenses.setText(String.valueOf(expensesToIncome));
I have updated my answer
For passing double value between Activity:
Intent inent = new Intent(thisActivity.this, nextActivity.class);
Bundle b = new Bundle();
b.putDouble("myincome", myIncome); // myIncome is your double value here
intent.putExtras(b);
startActivity(intent);
To get value in next Activity:
Bundle b = getIntent().getExtras();
double myIncome = b.getDouble("myincome");
Check your procedure of passing double value, I have mentioned it above
Edited XML Layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tv_BigHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Your Grade:"
android:textSize="40sp" />
<TextView
android:id="#+id/tv_Grade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_BigHeading"
android:layout_centerHorizontal="true"
android:text="A"
android:textSize="80sp"
android:textStyle="bold" />
<TextView
android:id="#+id/messageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_Grade"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:text="You are living well within your means! You could probably afford to spend more. Either way, great work!"
android:textSize="14sp" />
<TextView
android:id="#+id/yourIncome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/messageView"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="Monthly Income:"
android:textColor="#000000"
android:textSize="14sp" />
<TextView
android:id="#+id/incomeValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/messageView"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:layout_toRightOf="#+id/yourIncome"
android:background="#ff77ff75"
android:text="1000 $"
android:textColor="#000000"
android:textSize="14sp" />
<TextView
android:id="#+id/yourExpenses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/yourIncome"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:text="Expenses:"
android:textColor="#000000"
android:textSize="14sp" />
<TextView
android:id="#+id/expenseValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/incomeValue"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:layout_toRightOf="#+id/yourExpenses"
android:background="#ff77ff75"
android:text="1000 $"
android:textColor="#000000"
android:textSize="14sp" />
<TextView
android:id="#+id/Expenses_Income"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/yourExpenses"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:text="Expenses/Income:"
android:textColor="#000000"
android:textSize="14sp" />
<TextView
android:id="#+id/Expenses_Income_Value"
android:layout_width="wrap_content"
android:layout_height="16dp"
android:layout_below="#+id/expenseValue"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:layout_toRightOf="#+id/Expenses_Income"
android:background="#ff77ff75"
android:text="1000 $"
android:textColor="#000000"
android:textSize="14sp" />
<TextView
android:id="#+id/tips"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/Expenses_Income"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:text="Here are some tips:"
android:textColor="#000000"
android:textSize="16sp" />
</RelativeLayout>
</ScrollView>
This will solve your issue now, and use all my recommendations e.g: income.setText(String.valueOf(myIncome);
for setting the textview values

How to write if else to get value from edit text android

I have this 3 types of edit text input.
I want to compare the 3 edit text to get the FreeTime.
xml codes
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/morningLabel"
android:id="#+id/MorningLabel"
android:textStyle="bold"
android:layout_alignTop="#+id/textView2"
android:layout_alignRight="#+id/MorningText"
android:layout_alignEnd="#+id/MorningText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Working Hour(s)"
android:id="#+id/textView3"
android:layout_centerHorizontal="true"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Afternoon"
android:id="#+id/textView2"
android:textStyle="bold"
android:layout_alignTop="#+id/textView5"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Evening"
android:id="#+id/textView5"
android:textStyle="bold"
android:layout_marginBottom="41dp"
android:layout_above="#+id/AfternoonText"
android:layout_toRightOf="#+id/textView3"
android:layout_toEndOf="#+id/textView3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=" 6.01 a.m. \n to \n12.00 p.m."
android:id="#+id/morningTime"
android:textStyle="italic"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/textView3"
android:layout_toStartOf="#+id/textView3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=" 12.01 p.m. \n to \n 6.00 p.m."
android:id="#+id/afternoonTime"
android:textStyle="italic"
android:layout_alignTop="#+id/morningTime"
android:layout_alignLeft="#+id/textView2"
android:layout_alignStart="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=" 6.01 p.m. \n to \n12.00 a.m."
android:id="#+id/eveningTime"
android:textStyle="italic"
android:layout_alignTop="#+id/afternoonTime"
android:layout_alignLeft="#+id/EveningText"
android:layout_alignStart="#+id/EveningText" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result"
android:id="#+id/btnNext"
android:layout_alignParentBottom="true"
android:layout_marginBottom="38dp"
android:layout_alignRight="#+id/eveningTime"
android:layout_alignEnd="#+id/eveningTime"
android:layout_alignLeft="#+id/morningTime"
android:layout_alignStart="#+id/morningTime"
android:textStyle="bold" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/MorningText"
android:hint="0-6"
android:layout_marginBottom="22dp"
android:autoText="true"
android:background="#ffd1d1d1"
android:editable="false"
android:textSize="#dimen/abc_text_size_display_1_material"
android:layout_above="#+id/morningTime"
android:layout_toLeftOf="#+id/textView3"
android:layout_alignLeft="#+id/morningTime"
android:layout_alignStart="#+id/morningTime"
android:text="#string/MorningInput"
android:singleLine="false"
android:textAlignment="center"
android:numeric="integer" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/AfternoonText"
android:hint="0-6"
android:autoText="true"
android:background="#ffd1d1d1"
android:editable="false"
android:textSize="#dimen/abc_text_size_display_1_material"
android:layout_alignTop="#+id/MorningText"
android:layout_alignLeft="#+id/afternoonTime"
android:layout_alignStart="#+id/afternoonTime"
android:layout_alignRight="#+id/afternoonTime"
android:layout_alignEnd="#+id/afternoonTime"
android:text="#string/AfternoonInput"
android:textAlignment="center"
android:numeric="integer" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/EveningText"
android:hint="0-6"
android:autoText="true"
android:background="#ffd1d1d1"
android:editable="false"
android:textSize="#dimen/abc_text_size_display_1_material"
android:layout_alignBaseline="#+id/AfternoonText"
android:layout_alignBottom="#+id/AfternoonText"
android:layout_alignRight="#+id/textView5"
android:layout_alignEnd="#+id/textView5"
android:text="#string/EveningInput"
android:textAlignment="center"
android:numeric="integer"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/timeLabel"
android:id="#+id/TimeText"
android:layout_above="#+id/btnNext"
android:layout_alignLeft="#+id/btnNext"
android:layout_alignStart="#+id/btnNext" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="c"
android:onClick="calculateClickHandler"
android:id="#+id/btnc"
android:layout_above="#+id/TimeText"
android:layout_toRightOf="#+id/afternoonTime"
android:layout_toEndOf="#+id/afternoonTime"
android:layout_marginBottom="42dp" />
This is the java code. I think I put the wrong if else. How can I solve this? Anyone help:
public class WorkingHour extends Activity
{
public void calculateClickHandler(View view)
{
if (view.getId() == R.id.btnc)
{
Intent i=new Intent(this, Result.class);
// get the references to the widgets
EditText MorningInput = (EditText)findViewById(R.id.MorningText);
EditText AfternoonInput = (EditText)findViewById(R.id.AfternoonText);
EditText EveningInput = (EditText)findViewById(R.id.EveningText);
TextView TimeText = (TextView)findViewById(R.id.TimeText);
// get the users values from the widget references
int morninghour = Integer.parseInt(MorningInput.getText().toString());
int afternoonhour = Integer.parseInt(AfternoonInput.getText().toString());
int eveninghour = Integer.parseInt(EveningInput.getText().toString());
// calculate the free time
int freeTimeValue = calculateFreeTime(morninghour,afternoonhour,eveninghour);
// interpret the meaning of the bmi value
String freetimeInterpretation = interpretFT(freeTimeValue);
// now set the value in the result text
TimeText.setText(freeTimeValue + "-" + freetimeInterpretation);
SharedPreferences sp2 = getSharedPreferences("name2",MODE_PRIVATE);
SharedPreferences.Editor editor=sp2.edit();
editor.putString("rslt 3",TimeText.getText().toString());
editor.commit();
}
}
// the formula to calculate the free time
private int calculateFreeTime (int morninghour, int afternoonhour, int eveninghour)
{
if (((6- morninghour)> (6-afternoonhour)) && ((6- morninghour)> (6-eveninghour)))
{
return (int) (6 - morninghour);
}
else if (((6- afternoonhour)> (6-morninghour)) && ((6- afternoonhour)> (6-eveninghour)))
{
return (int) (6 - afternoonhour);
}
else if (((6- eveninghour)> (6-morninghour)) && ((6-eveninghour)> (6-afternoonhour)))
{
return (int) (6 - eveninghour);
}
return 0;
}
This code:
if (freetime < )
{
return "morning";
}
Is definitely wrong and should not even compile. You are saying here: if freetime is smaller than nothing... do something. You have to put a value in it (these are for example):
if (freetime < 6)
{
return "morning";
}
else if (freetime < 12)
{
return "Afternoon";
}
Also, there is no need to cast this return value because it are both integers:
return (int) (6 - morninghour);
^^
If you want to make your code a little better (mainly for readability), you can optimize this:
morninghour = 6 - morninghour;
afternoonhour = 6 - afternoonhour;
eveninghour = 6 - eveninghour;
if ((morninghour > afternoonhour) && (morninghour > eveninghour))
{
return morninghour;
}
else if ((afternoonhour > morninghour) && (afternoonhour > eveninghour))
{
return afternoonhour;
}
else if ((eveninghour > morninghour) && (eveninghour > afternoonhour))
{
return eveninghour;
}
return 0;

Simple calculator program not showing proper output

I have some simple code where I input two numbers in EditText fields, add them together, and show them in a TextView.
Here is my code:
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:visibility="invisible"/>
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="21dp"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_alignRight="#+id/editText2"
android:text="Clear"
android:onClick="Clicked" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText2"
android:layout_marginTop="35dp"
android:text="Total"
android:onClick="Clicked" />
And here is my Clicked method:
public void Clicked(View v) {
int total;
EditText t1= (EditText)findViewById(R.id.editText1);
EditText t2= (EditText)findViewById(R.id.editText2);
TextView tv= (TextView)findViewById(R.id.textView1);
if(v.getId()==R.id.button1)
{
total= Integer.parseInt(t1.getText().toString()+t2.getText().toString());
tv.setText(total);
tv.setVisibility(1);
}
else if (v.getId()==R.id.button2)
{
t1.setText("");
t2.setText("");
}
}
I input two numbers and when I press clear it works fine but the total button does not add. Instead, this happens:
It might be a problem with my integer casting or a problem with logic.
Change this:
total= Integer.parseInt(t1.getText().toString()+t2.getText().toString());
To this:
int v1 = Integer.parseInt(t1.getText().toString());
int v2 = Integer.parseInt(t2.getText().toString());
total = v1 + v2;
Its stopped because you may be setting a Int value to setText of TextView. You need to convert it to String
textView.setText(CharSequence text)
int v1 = Integer.parseInt(t1.getText().toString());
int v2 = Integer.parseInt(t2.getText().toString());
total = v1 + v2;
tv.setText(total+""); //this converts total to string
//tv.setText(total.toString()); //can use either

Categories

Resources