Handling RadioGroup and Button Events in Android - java

I am a beginner in Android and I am trying to create a simple Android app
which has two Text boxes (EditText) to take two Numbers as Input. Then I am Creating Radio Group having four Radio Buttons (Add,Sub,Multiply,Divide).
Then I am having a Button to get the results. I am getting an AlertBox saying "Unfortunately, SimpleApp has stopped working" the moment I click the Button. Kindly assist me.
*Here is my Java code *
package com.example.simpleapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private EditText txt1;
private EditText txt2;
private String input1;
private String input2;
private Double Num1;
private Double Num2;
private String flag;
private EditText TextResult;
Double Result=0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControls();
}
private void initControls()
{
((Button)findViewById(R.id.button1)).setOnClickListener(this);
}
public void onradioButtonClicked(View view)
{
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId())
{
case R.id.radio0:
if(checked)
flag = "add";
//Result = Num1+Num2;
break;
case R.id.radio1:
if(checked)
flag = "sub";
//Result = Num1-Num2;
break;
case R.id.radio2:
if(checked)
flag = "prod";
//Result = Num1*Num2;
break;
case R.id.radio3:
if(checked)
flag = "div";
//Result = Num1/Num2;
break;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextResult = (EditText)findViewById(R.id.textView2);
TextResult.setText("0");
txt1 = (EditText)findViewById(R.id.editText1);
txt2 = (EditText)findViewById(R.id.editText2);
input1 = txt1.getText().toString();
input2 = txt2.getText().toString();
Num1 = Double.parseDouble(input1);
Num2 = Double.parseDouble(input2);
if(flag == "add")
Result = Num1+Num2;
else if(flag == "sub")
Result = Num1-Num2;
else if(flag == "prod")
Result = Num1*Num2;
else Result = Num1/Num2;
TextResult.setText(String.valueOf(Result));
}
}
Here is my Activity_Main.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="102dp"
android:layout_marginTop="66dp"
android:orientation="vertical" >
</LinearLayout>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/linearLayout1"
android:layout_marginTop="34dp" >
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tableRow1"
android:layout_below="#+id/tableRow1"
android:layout_marginLeft="14dp" >
</TableRow>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tableRow1"
android:layout_alignTop="#+id/tableRow2"
android:ems="10"
android:hint="Enter Second Number"
android:inputType="number" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Enter First Number"
android:inputType="number" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:text="Simple Calculator App"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText2"
android:layout_below="#+id/editText2"
android:layout_marginTop="36dp" >
</TableRow>
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/editText2" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Add"
android:onClick="onradioButtonClicked"/>
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sub"
android:onClick="onradioButtonClicked"/>
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Multiply"
android:onClick="onradioButtonClicked"/>
<RadioButton
android:id="#+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Divide"
android:onClick="onradioButtonClicked"/>
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_below="#+id/radioGroup1"
android:text="Check"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

Your if then statements have wrong syntax. Try this:
if(flag == "add"){
Result = Num1+Num2;
}else if(flag == "sub"){
Result = Num1-Num2;
}else if(flag == "prod"){
Result = Num1*Num2;
}else{
Result = Num1/Num2;
}

try this ... calculation on click as well as on radio button checked change
public class MainActivity extends Activity implements OnClickListener,
OnCheckedChangeListener {
private EditText txt1;
private EditText txt2;
// private String input1;
// private String input2;
private Double Num1;
private Double Num2;
// private String flag;
private TextView TextResult;
Double Result = 0.0;
RadioButton radio0, radio1, radio2, radio3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
findViewById(R.id.button1).setOnClickListener(this);
radio0 = (RadioButton) findViewById(R.id.radio0);
radio0.setOnCheckedChangeListener(this);
radio1 = (RadioButton) findViewById(R.id.radio1);
radio1.setOnCheckedChangeListener(this);
radio2 = (RadioButton) findViewById(R.id.radio2);
radio2.setOnCheckedChangeListener(this);
radio3 = (RadioButton) findViewById(R.id.radio3);
radio3.setOnCheckedChangeListener(this);
TextResult = (TextView) findViewById(R.id.textView2);
TextResult.setText("0");
txt1 = (EditText) findViewById(R.id.editText1);
txt2 = (EditText) findViewById(R.id.editText2);
}
public void onradioButtonClicked(View view) {
}
#Override
public void onClick(View v) {
getCalculationValue();
// input1 = txt1.getText().toString();
// input2 = txt2.getText().toString();
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getCalculationValue();
}
private void getCalculationValue() {
Num1 = Double.parseDouble(txt1.getText().toString().trim());
Num2 = Double.parseDouble(txt2.getText().toString().trim());
if (radio0.isChecked())
Result = Num1 + Num2;
else if (radio1.isChecked())
Result = Num1 - Num2;
else if (radio2.isChecked())
Result = Num1 * Num2;
else if (radio3.isChecked())
Result = Num1 / Num2;
TextResult.setText(String.valueOf(Result));
}
}

You are Typecasted TextView into EditText.
So Android rises ClassCastException
08-03 17:08:30.415: E/AndroidRuntime(7702): java.lang.ClassCastException: android.widget.TextView
private EditText TextResult;
TextResult = (EditText)findViewById(R.id.textView2);
Change these lines into
private TextView TextResult;
TextResult = (TextView) findViewById(R.id.textView2);

Related

My app crashes when an EditText is empty and I press a button

Why when I click the button and nothing is written in EditText, the program crashes?
The app is used to calculate the load securing.Users enter values ​​and get the number of straps they need.But when a field is free, the app crashes
Code:
public class Ladungssicherung extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
EditText stfinput;
EditText gewichtinput;
EditText winkelinput;
String text;
double k = 1.5;
int cZ = 1; // beschleunigungsbeiwert nach unten
double cX = 0.8; // beschleunigungsbeiwert nach vorne
Dialog epicDialog;
TextView unicode, ergebnissFeld;
ImageView muinfoButton, closemuButton, infoalphaButton;
#SuppressLint("StringFormatInvalid")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_ladungssicherung);
winkelinput = (EditText) findViewById(R.id.winkelInput);
ergebnissFeld = (TextView) findViewById(R.id.ergebniss);
gewichtinput = (EditText) findViewById(R.id.gewichtInput);
stfinput = (EditText) findViewById(R.id.stfInput);
SharedPreferences sharedPreferences = getSharedPreferences("sharedPrefs", MODE_PRIVATE);
text = sharedPreferences.getString("text", "");
winkelinput.setText(text);
sharedPreferences.edit().remove("text").commit();
epicDialog = new Dialog(this, android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen);
muinfoButton = (ImageView) findViewById(R.id.infomuIcon);
closemuButton = (ImageView) findViewById(R.id.closemuinfo);
infoalphaButton = (ImageView) findViewById(R.id.infoalpha);
muinfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showmuinfo();
}
});
infoalphaButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showalphawinkel();
}
});
//Spinner code
Spinner spinner = findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.numbers, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void showalphawinkel() {
Intent intent = new Intent(this, WinkelmessActivity.class);
startActivity(intent);
}
public void showmuinfo() {
epicDialog.setContentView(R.layout.muinfo);
closemuButton = (ImageView) epicDialog.findViewById(R.id.closemuinfo);
closemuButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
epicDialog.show();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void ergebnissFromel(View v) {
Spinner feld4 = (Spinner) findViewById(R.id.spinner1);
Integer zahl1 = Integer.parseInt(gewichtinput.getText().toString());
Integer zahl2 = Integer.parseInt(winkelinput.getText().toString());
Integer zahl3 = Integer.parseInt(stfinput.getText().toString());
String spinner = feld4.getSelectedItem().toString();
xml layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Ladungssicherung">
<ImageView
android:id="#+id/infoalpha"
android:layout_width="38dp"
android:layout_height="40dp"
android:layout_alignBottom="#+id/winkelInput"
android:layout_alignStart="#+id/infomuIcon"
app:srcCompat="#drawable/info_icon" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="97dp"
android:layout_height="34dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="223dp"
android:layout_toEndOf="#+id/textView">
</Spinner>
<TextView
android:id="#+id/textView"
android:layout_width="117dp"
android:layout_height="29dp"
android:layout_above="#+id/gewichtInput"
android:layout_alignStart="#+id/gewichtInput"
android:layout_marginBottom="-108dp"
android:text="Gewicht"
android:textSize="20sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/gewichtInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="108dp"
android:ems="10"
android:hint="kg"
android:inputType="textPersonName" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/winkelInput"
android:layout_marginBottom="-211dp"
android:layout_toStartOf="#+id/spinner1"
android:text="Winkel Alpha"
android:textSize="20sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/winkelInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="211dp"
android:ems="10"
android:hint="#string/alpha"
android:inputType="textPersonName" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/stfInput"
android:layout_alignStart="#+id/textView"
android:text="Vorspannkraft je Gurt"
android:textSize="20sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/stfInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView5"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="daN"
android:inputType="textPersonName" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="37dp"
android:layout_height="29dp"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/textView5"
android:layout_marginTop="116dp"
app:srcCompat="#drawable/gewicht" />
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="175dp"
android:background="#color/grau">
</View>
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="277dp"
android:background="#color/grau">
</View>
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="275dp"
android:background="#color/grau">
</View>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/spinner1"
android:layout_marginStart="46dp"
android:text="#string/mue"
android:textSize="25sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="15dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginEnd="-3dp"
android:layout_toStartOf="#+id/textView6"
android:text="S"
android:textSize="23sp" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/stfInput"
android:layout_marginStart="3dp"
android:layout_alignStart="#+id/textView4"
android:text="TF"
android:textSize="23sp" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/winkelInput"
android:layout_alignStart="#+id/textView4"
android:text="#string/alpha"
android:textSize="23sp" />
<ImageView
android:id="#+id/infomuIcon"
android:layout_width="38dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/spinner1"
android:layout_marginTop="-2dp"
android:layout_marginEnd="17dp"
app:srcCompat="#drawable/info_icon" />
<TextView
android:id="#+id/titelNiederzurren"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="21dp"
android:textSize="20sp"
android:textColor="#color/blue"
android:text="Niederzurren" />
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="199dp"
android:background="#color/grau">
</View>
<TextView
android:id="#+id/ergebniss"
android:layout_width="154dp"
android:layout_height="36dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="53dp"
android:background="#color/greensmiley"
android:text="" />
<Button
android:id="#+id/buttonladungssicherung"
android:layout_width="144dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="120dp"
android:text="Button"
android:onClick="ergebnissFromel"
/>
</RelativeLayout>
You are probably getting NumberFormatException because you are trying to parse empty String to Integer. Surround Integer.parseInt(gewichtinput.getText().toString()) lines with try catch blocks, and it should be fine.
Try these codes and let us get updated with what you see:
public void ergebnissFromel(View v) {
Spinner feld4 = (Spinner) findViewById(R.id.spinner1);
Integer zahl1 = 0;
Integer zahl2 = 0;
Integer zahl3 = 0;
try
{
zahl1 = Integer.parseInt(gewichtinput.getText().toString());
zahl2 = Integer.parseInt(winkelinput.getText().toString());
zahl3 = Integer.parseInt(stfinput.getText().toString());
} catch (Exception e) {
Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
String spinner = feld4.getSelectedItem().toString();
if ( zahl1.equals("") || zahl1 == null){
Toast.makeText(this, "Bitte geben Sie das Gewicht an", Toast.LENGTH_SHORT).show();
}
if ( zahl2.equals("") || zahl2 == null){
Toast.makeText(this, "Bitte geben Sie das Gewicht an", Toast.LENGTH_SHORT).show();
}
if ( zahl3.equals("") || zahl3 == null){
Toast.makeText(this, "Bitte geben Sie das Gewicht an", Toast.LENGTH_SHORT).show();
}
else {
// Grad wird in sinus alpha umgerechnet
double newsinus = Math.sin(Math.toRadians(Float.valueOf(zahl2)));
double wert1 = cX - Float.valueOf(spinner) * cZ;
double wert2 = Float.valueOf(spinner) * newsinus;
// Formel Niederzurren Algorithmus
double wert3 = wert1 * zahl1;
double wert4 = wert2 * k;
double wert5 = wert3 / wert4;
double wert6 = Math.round(wert5);
double wert7 = wert6 / zahl3;
double wert8 = Math.ceil(wert7);
ergebnissFeld.setText(String.valueOf(Math.round(wert8)));
}
}
Usually when your app crashes, you'll find a stack trace logged that will help you understand where the problem is. You can find the log within Android Studio's Debug|Console tab. Alternatively you can use the adb command from a terminal/shell window. I like using "adb logcat -v time".
Before parsing to integer, you should check wether the input is null.
Furthermore, you're calling a method on zahl1 and check wether it is null afterwards.
String strZahl1 = gewichtinput.getText().toString(); //Get input as String
if(strZahl1 == null || strZahl1.isEmpty()) //First make sure that strZahl1 is not null, then check wether it is empty
{
Toast.makeText(this, "Bitte geben Sie das Gewicht an",Toast.LENGTH_SHORT).show();
}
Integer zahl1 = Integer.parseInt(strZahl1);
If the user is able to enter something else than a number into your textfields, you could surround the parsing with a try block:
Integer zahl1;
try
{
zahl1 = Integer.parseInt(strZahl1);
}
catch(NumberFormatException e)
{
Toast.makeText(this, strZahl1 + " ist keine gültige Zahl", Toast.LENGTH_SHORT).show();
}
Your app crashes because .getText().toString is an empty string. Java cannot convert an empty string into an integer.
A better way is to do something like
Integer zahl1 ;
if((gewichtinput.getText() != null) && (!gewichtinput.getText().toString.isEmpty()))
{
zahl1 = Integer.parseInt(gewichtinput.getText().toString());
}
else
{
zahl1 = 0 ;
}
Do the same for all the other edit texts.
It should hopefully work

Android - How do I keep a button clicked (Selected)?

I am trying to build a calculator with two TextView fields for the two numbers. I figured out how to input the numbers using an "in-app" number pad for the top number, Operand 1 [textView] (I know it would be easier using an EditText but this is for an assignment). I am having trouble switching to the second textView, Operand 2 [textView2].
When I am done input the number for textView, I want to switch to textView2 (using the plus, minus, mult, and/or div Buttons) and continue to enter in the numbers so I can use it for calculations.
Here is an Image of what my app looks like. Please ignore the stars, progress bar, and raido buttons as they are apart of the assignment but not relevent to the calculator.
Do you have any suggestion about how I can do this?
Android Code
package com.example.tristan.assn2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
String operand1 = "";
String operand2 = "";
String oneS = "1";
String twoS = "2";
String threeS = "3";
String fourS = "4";
String fiveS = "5";
String sixS = "6";
String sevenS = "7";
String eightS = "8";
String nineS = "9";
String zeroS = "0";
String dotS = ".";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendMessage(View view)
{
Button clickedButton = (Button) view;
Button one = (Button) findViewById(R.id.button);
Button two = (Button) findViewById(R.id.button2);
Button three = (Button) findViewById(R.id.button3);
Button four = (Button) findViewById(R.id.button4);
Button five = (Button) findViewById(R.id.button5);
Button six = (Button) findViewById(R.id.button6);
Button seven = (Button) findViewById(R.id.button7);
Button eight = (Button) findViewById(R.id.button8);
Button nine = (Button) findViewById(R.id.button9);
Button zero = (Button) findViewById(R.id.button10);
Button dot = (Button) findViewById(R.id.button11);
Button clear = (Button) findViewById(R.id.button12);
Button plus = (Button) findViewById(R.id.button17);
Button minus = (Button) findViewById(R.id.button15);
Button mult = (Button) findViewById(R.id.button19);
Button div = (Button) findViewById(R.id.button21);
Button sr = (Button) findViewById(R.id.button16);
Button fac = (Button) findViewById(R.id.button20);
Button dd = (Button) findViewById(R.id.button22);
Button equal = (Button) findViewById(R.id.button23);
//------------------------------------------------------------------------------------------
TextView textView = (TextView) findViewById(R.id.textView);
TextView textView2 = (TextView) findViewById(R.id.textView2);
//OPERAND1
if(clickedButton == minus) {
operand1 = "-";
list1.add(operand1);
}
if (clickedButton == one) {
operand1 = oneS;
list1.add(operand1);
}
if (clickedButton == two) {
operand1 = twoS;
list1.add(operand1);
}
if (clickedButton == three) {
operand1 = threeS;
list1.add(operand1);
}
if (clickedButton == four) {
operand1 = fourS;
list1.add(operand1);
}
if (clickedButton == five) {
operand1 = fiveS;
list1.add(operand1);
}
if (clickedButton == six) {
operand1 = sixS;
list1.add(operand1);
}
if (clickedButton == seven) {
operand1 = sevenS;
list1.add(operand1);
}
if (clickedButton == eight) {
operand1 = eightS;
list1.add(operand1);
}
if (clickedButton == nine) {
operand1 = nineS;
list1.add(operand1);
}
if (clickedButton == zero) {
operand1 = zeroS;
list1.add(operand1);
}
if (clickedButton == dot) {
operand1 = dotS;
list1.add(operand1);
}
//Builds String from ArrayList
StringBuilder sb1 = new StringBuilder();
for (String s1 : list1) {
sb1.append(s1);
}
//STRING NUMBER
String output1 = sb1.toString();
textView.setText(output1);
//NEED TO CONVERT TO DOUBLE*****************
//IF plus, minus, mult, div is pressed, switch to Operand 2 and input numbers
if(clickedButton == plus || clickedButton == minus || clickedButton == mult || clickedButton == div) {
if (clickedButton == one) {
operand2 = oneS;
list2.add(operand2);
}
if (clickedButton == two) {
operand2 = twoS;
list2.add(operand2);
}
if (clickedButton == three) {
operand2 = threeS;
list2.add(operand2);
}
if (clickedButton == four) {
operand2 = fourS;
list2.add(operand2);
}
if (clickedButton == five) {
operand2 = fiveS;
list2.add(operand2);
}
if (clickedButton == six) {
operand2 = sixS;
list2.add(operand2);
}
if (clickedButton == seven) {
operand2 = sevenS;
list2.add(operand2);
}
if (clickedButton == eight) {
operand2 = eightS;
list2.add(operand2);
}
if (clickedButton == nine) {
operand2 = nineS;
list2.add(operand2);
}
if (clickedButton == zero) {
operand2 = zeroS;
list2.add(operand2);
}
if (clickedButton == dot) {
operand2 = dotS;
list2.add(operand2);
}
//Builds String from ArrayList
StringBuilder sb2 = new StringBuilder();
for (String s2 : list2) {
sb2.append(s2);
}
//STRING NUMBER
String output2 = sb2.toString();
textView2.setText(output2);
}
}
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.tristan.assn2.MainActivity">
<Button
android:text="/"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button21"
android:fontFamily="sans-serif-medium"
android:layout_alignBaseline="#+id/button18"
android:layout_alignBottom="#+id/button18"
android:layout_toRightOf="#+id/button18"
android:layout_alignRight="#+id/button15"
android:layout_alignEnd="#+id/button15"
android:onClick="sendMessage"/>
<Button
android:text="3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button3"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="sendMessage"/>
<Button
android:text="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_toLeftOf="#+id/button3"
android:layout_toStartOf="#+id/button3"
android:onClick="sendMessage"/>
<Button
android:text="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_marginBottom="61dp"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/button2"
android:layout_toStartOf="#+id/button2"
android:onClick="sendMessage"/>
<Button
android:text="4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button4"
android:layout_above="#+id/button2"
android:layout_alignLeft="#+id/button11"
android:layout_alignStart="#+id/button11"
android:onClick="sendMessage"/>
<Button
android:text="5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button2"
android:layout_toLeftOf="#+id/button3"
android:layout_toStartOf="#+id/button3"
android:id="#+id/button5"
android:onClick="sendMessage"/>
<Button
android:text="6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button5"
android:layout_toRightOf="#+id/button2"
android:layout_toEndOf="#+id/button2"
android:id="#+id/button6"
android:onClick="sendMessage"/>
<Button
android:text="7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button7"
android:layout_above="#+id/button4"
android:layout_alignLeft="#+id/button4"
android:layout_alignStart="#+id/button4"
android:onClick="sendMessage"/>
<Button
android:text="8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button7"
android:layout_toRightOf="#+id/button4"
android:layout_toEndOf="#+id/button4"
android:id="#+id/button8"
android:onClick="sendMessage"/>
<Button
android:text="9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button6"
android:layout_toRightOf="#+id/button5"
android:id="#+id/button9"
android:layout_alignTop="#+id/button8"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="sendMessage"/>
<Button
android:text="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button3"
android:layout_toLeftOf="#+id/button3"
android:layout_toStartOf="#+id/button3"
android:id="#+id/button10"
android:onClick="sendMessage"/>
<Button
android:text="."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button10"
android:layout_toLeftOf="#+id/button2"
android:id="#+id/button11"
android:layout_below="#+id/button5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="87dp"
android:layout_marginStart="87dp"
android:layout_marginTop="47dp"
android:onClick="sendMessage"/>
<Button
android:text="-"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button15"
android:layout_alignTop="#+id/button7"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="41dp"
android:layout_marginStart="41dp"
android:layout_toLeftOf="#+id/button4"
android:layout_toStartOf="#+id/button4"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:onClick="sendMessage"/>
<Button
android:text="+"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button17"
android:layout_alignBaseline="#+id/button15"
android:layout_alignBottom="#+id/button15"
android:layout_toStartOf="#+id/button4"
android:layout_toLeftOf="#+id/button4"
android:layout_marginRight="47dp"
android:layout_marginEnd="47dp"
android:onClick="sendMessage" />
<Button
android:text="x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button18"
android:layout_below="#+id/button17"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/button17"
android:layout_alignEnd="#+id/button17"
android:fontFamily="sans-serif-medium"
android:onClick="sendMessage"/>
<Button
android:text="x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button19"
android:layout_below="#+id/button17"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/button17"
android:layout_alignEnd="#+id/button17"
android:fontFamily="sans-serif-medium"
android:onClick="sendMessage"/>
<Button
android:text="sr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button16"
android:fontFamily="sans-serif-medium"
android:layout_below="#+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/button20"
android:layout_toStartOf="#+id/button20"
android:onClick="sendMessage"/>
<Button
android:text="!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button20"
android:fontFamily="sans-serif-medium"
android:layout_below="#+id/button21"
android:layout_alignLeft="#+id/button15"
android:layout_alignStart="#+id/button15"
android:layout_alignRight="#+id/button21"
android:layout_alignEnd="#+id/button21"
android:onClick="sendMessage"/>
<Button
android:text="DD - DMS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button11"
android:layout_toStartOf="#+id/button"
android:id="#+id/button22"
android:layout_alignRight="#+id/button20"
android:layout_alignEnd="#+id/button20"
android:onClick="sendMessage"/>
<TextView
android:hint="Operand 1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView"
android:layout_toLeftOf="#+id/button5"
android:layout_toStartOf="#+id/button5" />
<TextView
android:hint="Operand 2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="13dp"
android:id="#+id/textView2"
android:layout_toLeftOf="#+id/button8"
android:layout_toStartOf="#+id/button8" />
<TextView
android:hint="Results"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/textView3"
android:layout_toRightOf="#+id/textView"
android:layout_toEndOf="#+id/textView" />
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ratingBar"
android:isIndicator="false"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_alignBottom="#+id/ratingBar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp" />
<RadioButton
android:text="Use for Operand 1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioButton"
android:layout_below="#+id/button23"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<RadioButton
android:text="Use for Operand 2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioButton"
android:layout_alignLeft="#+id/radioButton"
android:layout_alignStart="#+id/radioButton"
android:id="#+id/radioButton2" />
<Button
android:text="="
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button23"
android:layout_alignTop="#+id/textView2"
android:layout_toRightOf="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="sendMessage"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_below="#+id/radioButton2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="C"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button12"
android:layout_alignBaseline="#+id/button10"
android:layout_alignBottom="#+id/button10"
android:layout_toRightOf="#+id/button8"
android:layout_toEndOf="#+id/button8"
android:onClick="sendMessage"/>
</RelativeLayout>
You have to listen the key clicks after the plus/minus/.. button clicks occurs. Use a flag. set the flag 1 when plus/minus/.. or textview2 gets clicked and change the textview to textview2 and list1 to list2. Do the vice versa when textview1 is clicked.
you can do something like this :
public class YourActivityName extends AppCompatActivity {
TextView operand1, operand2,result,tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dd);
operand1 = (TextView) findViewById(R.id.textView);
operand2 = (TextView) findViewById(R.id.textView2);
result= (TextView) findViewById(R.id.textView3);
tv=operand1;
}
public void sendMessage(View v) {
if (v.getId() == R.id.button19 || v.getId() == R.id.button15 || v.getId() == R.id.button17 || v.getId() == R.id.button21 || v.getId() == R.id.button18) {
tv=operand2;
}
if(v.getId()==R.id.button7){
tv.setText(tv.getText()+"7");
}
if(v.getId()==R.id.button8){
tv.setText(tv.getText()+"8");
}
if(v.getId()==R.id.button23){
int op1=Integer.parseInt(operand1.getText().toString());
int op2=Integer.parseInt(operand2.getText().toString());
op2+=op1;
result.setText(op2+"");
tv=operand1;
operand1.setText("");
operand2.setText("");
}
}
}
this is code only for having addition on pressing '=' button and for taking input only from button '7' and '8' you need to and functionality for other buttons and operations ..but it should solve your problem of changing textview for input...
you can also do by means of flags . as suggested by #Code-Apprentice ...
You should toggle a boolean flag whenever the user clicks an operator button. Then when the user clicks a number button, check this flag to determine which operand is being used.
In conjunction with this flag, you can also have a variable like TextView currentTextView which is assigned to refer to the currently used TextView. Then whenever the user clicks an operator button, assign this variable to the other TextView. This strategy will make it so you only need if statements in the OnClickListeners for the operator buttons. You won't need any if statements in the OnClickListeners for the number buttons.
p.s. Note that every number button already displays the numerical character. You can use this fact to remove nearly all of the if...else chain in your click listener.
p.p.s. You should consider writing different OnClickListeners for each button. With the previously mentioned strategy, you can have a single listener for all the number buttons, but I still suggest creating a different listener for each operator button.

Activity to Fragment error having trouble getting value to shared preferences

I'm currently developing a calorie app for my class project. I had started using a activity for the layout but my professor wants me to use a fragment instead. While trying to convert the code to fragment I came across some issues having difficulty saving the value to the shared preference xml. The page i'm currently working on gets information from the user and depending what the user selects determines their calories. That value is then saved in shared preference where it is displayed in the main activity.
Thanks in advance for the help, I'm new to android studio and developing apps.
profile java file
`public class Profile extends Fragment implements View.OnClickListener {
//adaptors spinners
ArrayAdapter<String> HeightFeetAdapter;
ArrayAdapter<String> WeightLBSAdapter;
//references UI elements
Button SaveButton;
Spinner weightSpinner;
Spinner heightSpinner;
Spinner goal;
Spinner gender;
Spinner activityLevel;
EditText age;
private Animation anim;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_profile, container,
false);
String username =
getActivity().getIntent().getStringExtra("Username");
TextView userMain = (TextView) myView.findViewById(R.id.User);
userMain.setText(username);
age =(EditText)myView.findViewById(R.id.editText3);
age.setInputType(InputType.TYPE_CLASS_NUMBER);
heightSpinner = (Spinner) myView.findViewById(R.id.HeightSpin);
weightSpinner = (Spinner) myView.findViewById(R.id.WeightSpin);
activityLevel = (Spinner) myView.findViewById(R.id.activity_level);
ArrayAdapter<CharSequence> adapter_activity =
ArrayAdapter.createFromResource(getActivity(),
R.array.activity_level, android.R.layout.simple_spinner_item);
adapter_activity.setDropDownViewResource
(android.R.layout.simple_spinner_dropdow
n_item);
activityLevel.setAdapter(adapter_activity);
goal = (Spinner) myView.findViewById(R.id.goal);
ArrayAdapter<CharSequence> adapter_goal =
ArrayAdapter.createFromResource(getActivity(),
R.array.goal, android.R.layout.simple_spinner_item);
adapter_goal.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
goal.setAdapter(adapter_goal);
gender = (Spinner) myView.findViewById(R.id.gender);
ArrayAdapter<CharSequence> adapter_gender =
ArrayAdapter.createFromResource(getActivity(),
R.array.gender, android.R.layout.simple_spinner_item);
adapter_gender.setDropDownViewResource
(android.R.layout.simple_list_item_activated_1);
gender.setAdapter(adapter_gender);
SaveButton = (Button) myView.findViewById(R.id.savebutton);
SaveButton.setOnClickListener(this);
initializeSpinnerAdapters();
loadLBVal();
loadFTVal();
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
heightSpinner.startAnimation(anim);
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
weightSpinner.startAnimation(anim);
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
SaveButton.startAnimation(anim);
SharedPreferences userInfo =
PreferenceManager.getDefaultSharedPreferences(getActivity());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
return myView;
}
public void loadLBVal() {
weightSpinner.setAdapter(WeightLBSAdapter);
// set the default lib value
weightSpinner.setSelection(WeightLBSAdapter.getPosition("170"));
}
// load the feets value range to the height spinner
public void loadFTVal() {
heightSpinner.setAdapter(HeightFeetAdapter);
// set the default value to feets
heightSpinner.setSelection(HeightFeetAdapter.getPosition("5\"05'"));
}
public void initializeSpinnerAdapters() {
String[] weightLibs = new String[300];
// loading spinner values for weight
int k = 299;
for (int i = 1; i <= 300; i++) {
weightLibs[k--] = String.format("%3d", i);
}
// initialize the weightLibsAdapter with the weightLibs values
WeightLBSAdapter = new ArrayAdapter<String>(getContext(),
R.layout.activity_spinner_item, weightLibs);
WeightLBSAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
String[] heightFeets = new String[60];
// loading values 3"0' to 7"11' to the height in feet/inch
k = 59;
for (int i = 3; i < 8; i++) {
for (int j = 0; j < 12; j++) {
heightFeets[k--] = i + "\"" + String.format("%02d", j) + "'";
}
}
// initialize the heightFeetAdapter with the heightFeets values
HeightFeetAdapter = new ArrayAdapter<String>(getContext(),
R.layout.activity_spinner_item, heightFeets);
HeightFeetAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.savebutton:
int activityLevel, goal, gender, age;
// Get preferences
float height = getSelectedHeight();
float weight = getSelectedWeight();
activityLevel =
((Spinner)getActivity().findViewById
(R.id.activity_level)).getSelectedItemPosition();
goal = ((Spinner)getActivity().
findViewById(R.id.goal)).getSelectedItemPosition();
gender= ((Spinner)getActivity().
findViewById(R.id.gender)).getSelectedItemPosition();
age = Integer.parseInt(((EditText).
getActivity().findViewById(R.id.editText3)));
int tdee = calculateTDEE(height,weight,activityLevel,age,gender,
goal);
// Save preferences in XML
SharedPreferences userInfo = getSharedPreferences("userInfo",
0);
SharedPreferences.Editor editor = userInfo.edit();
editor.putInt("tdee", tdee);
editor.commit();
break;
}
}
public float getSelectedWeight() {
String selectedWeightValue = (String)weightSpinner.getSelectedItem();
return (float) (Float.parseFloat(selectedWeightValue) * 0.45359237);
}
public float getSelectedHeight() {
String selectedHeightValue = (String)heightSpinner.getSelectedItem();
// the position is feets and inches, so convert to meters and return
String feets = selectedHeightValue.substring(0, 1);
String inches = selectedHeightValue.substring(2, 4);
return (float) (Float.parseFloat(feets) * 0.3048) +
(float) (Float.parseFloat(inches) * 0.0254);
}
public int calculateTDEE(float height, float weight, int activityLevel,
int
age, int gender, int goal) {
double bmr = (10 * weight) + (6.25 * height) - (5 * age) + 5;
if(gender == 1) {
bmr = (10* weight) + (6.25 * height) - (5*age) - 161;
}
double activity = 1.25;
switch(activityLevel) {
case 1:
activity = 1.375;
break;
case 2:
activity = 1.55;
break;
case 3:
activity = 1.725;
break;
case 4:
activity = 1.9;
break;
}
double tdee = bmr * activity;
switch(goal) {
case 0:
tdee -=500;
break;
case 2:
tdee +=500;
break;
}
tdee += .5;
return (int) tdee;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
`
fragment_profile xml
`
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/imgbackground2"
android:weightSum="1">
<TextView
android:layout_width="180dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/emptyString"
android:id="#+id/User"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_alignParentTop="true"
android:layout_alignEnd="#+id/tv_main_title" />
<TextView
android:layout_width="294dp"
android:layout_height="65dp"
android:text="Please Complete Information"
android:textColor="#color/colorBackground"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:textSize="20dp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Age"
android:id="#+id/textView12"
android:layout_above="#+id/gender"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<EditText
android:layout_width="50dp"
android:layout_height="50dp"
android:inputType="number"
android:ems="10"
android:id="#+id/editText3"
android:imeOptions="actionDone"
android:layout_alignTop="#+id/gender"
android:layout_alignLeft="#+id/editText"
android:layout_marginLeft="0dp"
android:layout_column="1" />
</TableRow>
</TableLayout>
<RelativeLayout
android:layout_width="194dp"
android:layout_height="26dp"></RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Gender"
android:id="#+id/textView11"
/>
<Spinner
android:layout_width="113dp"
android:layout_height="40dp"
android:id="#+id/gender"
android:layout_above="#+id/textView5"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_alignStart="#+id/textView4"
android:layout_alignEnd="#+id/textView3"
android:spinnerMode="dropdown"
android:popupBackground="#color/colorBackground" />
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="329dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="#string/weightLabel"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/colorBackground"
android:textSize="25dp"
android:paddingRight="0dp"
android:paddingLeft="-2dp" />
<Spinner
android:id="#+id/WeightSpin"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:prompt="#string/weightLabel"
android:spinnerMode="dropdown"
android:layout_weight="2"
android:textAlignment="center"
android:popupBackground="#drawable/graybackground2"
android:layout_span="2"
android:layout_column="1" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="#string/heightLabel"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/colorBackground"
android:textSize="25dp"
android:layout_column="0"
android:layout_marginLeft="5dp" />
<Spinner
android:id="#+id/HeightSpin"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:prompt="#string/heightLabel"
android:layout_weight="2"
android:popupBackground="#drawable/graybackground2"
android:spinnerMode="dropdown"
android:layout_marginTop="0dp"
android:layout_margin="0dp"
android:layout_marginBottom="0dp"
android:layout_column="1"
android:paddingTop="0dp"
android:paddingBottom="0dp"
android:textAlignment="center"
android:paddingStart="5dp"
android:layout_marginLeft="0dp"
android:layout_span="0"
android:layout_marginRight="0dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Activity Level"
android:id="#+id/textView7"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<Spinner
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/activity_level"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Goal"
android:id="#+id/textView8"
android:layout_below="#+id/activity_level"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<Spinner
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/goal"
android:layout_below="#+id/textView8"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:spinnerMode="dropdown" />
</TableRow>
</TableLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/savebutton"
android:radius="10dp"
android:textColor="#color/colorBackground"
android:onClick="saveAction"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#+id/editText3"
android:layout_gravity="right" />
</LinearLayout>
`
Fragmenthome.java
import java.util.ArrayList;
public class FragmentHome extends Fragment implements
View.OnClickListener {
private TextView caloriesTotal;
private TextView caloriesRemain;
private ListView listView;
private LinearLayout mLayout;
private Animation anim;
ImageButton AddEntrybtn;
ImageButton ResetEntry;
Context context;
int goalCalories;
int totalCalorie;
Button mButton;
//Database
private DatabaseHandler dba;
private ArrayList<Food> dbFoods = new ArrayList<>();
private CustomListViewAdapter foodAdapter;
private Food myFood ;
//fragment
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container,
false);
caloriesTotal = (TextView) myView.findViewById(R.id.tv_calorie_amount);
caloriesRemain = (TextView) myView.findViewById(R.id.calorieRemain);
listView = (ListView) myView.findViewById(R.id.ListId);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
"2000"));
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain) getActivity()).loadSelection(4);
}
});
ResetEntry = (ImageButton) myView.findViewById(R.id.ResetEntry);
ResetEntry.setOnClickListener(this);
refreshData();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
return myView;
}
public void reset () {
//
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList<Food> foodsFromDB = dba.getFoods();
//Loop
for (int i = 0; i < foodsFromDB.size(); i ++){
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood= new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.clear();
dbFoods.remove(myFood);
foodsFromDB.remove(myFood);
dba.deleteFood(foodId);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item,dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
}
public void refreshData (){
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList<Food> foodsFromDB = dba.getFoods();
totalCalorie = dba.totalCalories();
String formattedCalories = Utils.formatNumber(totalCalorie);
String formattedRemain = Utils.formatNumber(goalCalories -
totalCalorie);
//setting the editTexts:
caloriesTotal.setText("Total Calories: " + formattedCalories);
caloriesRemain.setText(formattedRemain);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
"2000"));
//Loop
for (int i = 0; i < foodsFromDB.size(); i ++){
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood= new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.add(myFood);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item,dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
anim= AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
listView.startAnimation(anim);
}
//save prefs
public void savePrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
//get prefs
public int loadPrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
return sharedPreferences.getInt(key, value);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView) getView().findViewById(R.id.User);
userMain.setText(username1);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
case R.id.action_settings:
Intent preferenceScreenIntent = new Intent(getContext(),
PreferenceScreenActivity.class);
startActivity(preferenceScreenIntent);
break;
case R.id.ResetEntry:
reset();
anim= AnimationUtils.loadAnimation(getActivity(),
R.anim.fading);
listView.startAnimation(anim);
break;
}
}
}
preference.xml
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="User Settings">
<EditTextPreference
android:title="Daily Calorie Amount"
android:inputType="number"
android:defaultValue="2000"
android:key="#string/prefs_key_daily_calorie_amount"
android:summary="#string/prefs_description_daily_calorie_amount" />
</PreferenceCategory>
</PreferenceScreen>
You can use getContext() or getActivity() before the functions you want to invoke. getContext().getSharedPreferences(), getContext().getFilesDir(), etc.

how can access the value of variable in setOnCheckedChangeListener listener from onclick

I want to access value of gender variable from onClick(View v).
value of gender produce in onCheckedChanged(RadioGroup arg0, int selectedId)
and I dont know how can access this value
MAIN ACTIVITY
package com.dietandroidproject;
import Databasedata.Person;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RadioGroup genderselected = (RadioGroup) findViewById(R.id.selectgender);
genderselected.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup arg0, int selectedId) {
selectedId=genderselected.getCheckedRadioButtonId();
RadioButton genderchoosed = (RadioButton) findViewById(selectedId);
gender = genderchoosed.getText().toString();
}
});
Button saveinformation = (Button) findViewById(R.id.saveinformation);
saveinformation.setOnClickListener(new View.OnClickListener() {
EditText weighttext = (EditText) findViewById(R.id.weighttext);
EditText heighttext = (EditText) findViewById(R.id.heighttext);
EditText usernametext = (EditText) findViewById(R.id.usernametext);
EditText agetext = (EditText) findViewById(R.id.agetext);
//RadioGroup genderselected = (RadioGroup) findViewById(R.id.selectgender);
Spinner activitytext = (Spinner) findViewById(R.id.chooseactivity);
Button saveinformation = (Button) findViewById(R.id.saveinformation);
//TextView genderchoosed = (TextView) findViewById(genderselected
//.getCheckedRadioButtonId());
//String gender = genderchoosed.getText().toString();
String pa = activitytext.getSelectedItem().toString();
#Override
public void onClick(View v) {
int weight = (int) Float.parseFloat(weighttext.getText()
.toString());
float height = Float.parseFloat(heighttext.getText()
.toString());
String username = usernametext.getText().toString();
int age = (int) Float.parseFloat(agetext.getText().toString());
String pa = activitytext.getSelectedItem().toString();
//BMI======================================================
int Bmivalue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(Bmivalue);
float idealweight = idealweight(weight, height, gender, pa, age);
double dailycalories=dailycalories(weight,height,gender,pa,age);
//DB insert====================================================
Person person = new Person();
person.setUsername(username);
person.setHeight(height);
person.setWeight(weight);
person.setAge(age);
person.setGender(gender);
person.setPa(pa);
person.setBmivalue(Bmivalue);
person.setBmiInterpretation(bmiInterpretation);
person.setIdealweight(idealweight);
person.setDailycalories(dailycalories);
Databasedata.DatabaseAdapter dbAdapter = new Databasedata.DatabaseAdapter(
MainActivity.this);
dbAdapter.insertPerson(person);
Toast.makeText(getApplicationContext(),
Bmivalue + "and you are" + bmiInterpretation,
Toast.LENGTH_LONG).show();
}
});
}
XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/backgroundmain"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/personinformation"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.98" >
<EditText
android:id="#+id/heighttext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/usernametext"
android:layout_below="#+id/usernametext"
android:ems="10"
android:hint="Enter Your Height" >
</EditText>
<EditText
android:id="#+id/usernametext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:ems="10"
android:hint="Enter Username" />
<EditText
android:id="#+id/weighttext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/heighttext"
android:layout_below="#+id/heighttext"
android:ems="10"
android:hint="Enter Your Weight" />
<EditText
android:id="#+id/agetext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/weighttext"
android:layout_below="#+id/weighttext"
android:ems="10"
android:hint="Enter Your Age" >
<requestFocus />
</EditText>
</RelativeLayout>
<View
android:layout_width="250dp"
android:layout_height="1dip"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#aaa" />
<RelativeLayout
android:id="#+id/choosegender"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.78" >
<TextView
android:id="#+id/choosefemaleormale"
android:layout_width="match_parent"
android:layout_height="30dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="10dip"
android:gravity="center"
android:text="Gender : "
android:textAlignment="center"
android:textColor="#555"
android:textSize="19sp" />
<RadioGroup
android:id="#+id/selectgender"
android:layout_width="220dip"
android:layout_height="wrap_content"
android:layout_below="#+id/choosefemaleormale"
android:layout_centerHorizontal="true"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/femaleselected"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="1"
android:checked="true"
android:text="female"
/>
<RadioButton
android:id="#+id/maleselected"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="1"
android:text="male"
/>
</RadioGroup>
</RelativeLayout>
<View
android:layout_width="250dp"
android:layout_height="1dip"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="#aaa" />
<RelativeLayout
android:id="#+id/choosepa"
android:layout_width="250dip"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_gravity="center" >
<Spinner
android:id="#+id/chooseactivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:entries="#array/activityitems"
android:gravity="center"
android:prompt="#string/level_of_activity" />
</RelativeLayout>
<Button
android:layout_width="90dp"
android:layout_height="0dp"
android:layout_gravity="right"
android:layout_marginBottom="10dip"
android:layout_marginRight="20dp"
android:layout_weight="0.46"
android:background="#drawable/recent_foods_depressed"
android:hint="save"
android:text="save"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold"
android:onClick="saveinformation"
android:id="#+id/saveinformation"/>
</LinearLayout>
I need value of gender in float idealweight = idealweight(weight, height, gender, pa, age); and also double dailycalories=dailycalories(weight,height,gender,pa,age);
can any one help me?
String sex = null;
...
onCheckedChanged(RadioGroup arg0, int selectedId){
if(selectedId == R.id.femaleselected){
sex = "female";
} else {
sex = "male";
}
}
Hope this helps.
follow these steps:
add member String mGender to your activity.
MainActivity extend ...
String mGender = null;
onCreate ...
replace the gender by mGender and everything should work
onClick(View v) {
if(mGender != null){
// use mGender
// float gender = Float.valueOf(mGender);
//double gender = Double.valueOf(mGender);
}
}
genderselected.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup arg0, int selectedId)
{
switch(selectedId)
{
case R.id. femaleselected:
Log.d("","female selected");
break;
case R.id. maleselected:
Log.d("","male selected");
break;
}
}
});

Android simple Interest Calculator

I'm starter programmer on Android environment. And I need your help.
Here is the what I'm trying to do
package com.codeherenow.sicalculator;
import com.codeherenow.sicalculator.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
public class SICalculatorActivity extends Activity {
private TextView PA;
private TextView Interest_Rate;
private TextView Years;
private EditText PA_bar;
private EditText IR_bar;
private SeekBar year_bar;
private Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
PA = (TextView) findViewById(R.id.PA);
Interest_Rate = (TextView) findViewById(R.id.Interest_Rate);
Years= (TextView) findViewById(R.id.Years);
PA_bar= (EditText) findViewById(R.id.PA_bar);
IR_bar= (EditText) findViewById(R.id.IR_bar);
year_bar=(SeekBar) findViewById(R.id.year_bar);
calculate=(Button) findViewById(R.id.calculate);
calculate.setOnClickListener(new OnClickListener(){
public void onClick(View v){
}
}
}
}
My xml:
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SICalculatorActivity" >
<TextView
android:id="#+id/Years"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/IR_bar"
android:layout_centerVertical="true"
android:text="2 Year(s)"
android:textSize="20sp" />
<SeekBar
android:id="#+id/year_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Years"
android:layout_below="#+id/Years"
android:layout_marginTop="21dp" />
<Button
android:id="#+id/calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/year_bar"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/year_bar"
android:text="Calculate" />
<EditText
android:id="#+id/IR_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Years"
android:layout_marginBottom="14dp"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/Interest_Rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/IR_bar"
android:layout_alignLeft="#+id/IR_bar"
android:layout_marginBottom="15dp"
android:text="Interest Rate"
android:textSize="20sp" />
<TextView
android:id="#+id/PA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/PA_bar"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:text="Principal Amount"
android:textSize="20sp" />
<EditText
android:id="#+id/PA_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Interest_rate"
android:layout_below="#+id/PA"
android:layout_marginTop="17dp"
android:ems="10"
android:inputType="number" />
</RelativeLayout>
Actually , I need help for not xml part. I need help for java coding part. Even if i'm trying to use onclicklistener , compiler always show error on coding page? Could someone help me?
Try this:
public class MainActivity extends Activity {
TextView PA;
TextView Interest_Rate;
TextView Years;
EditText PA_bar;
EditText IR_bar;
EditText year_bar;
Button calculate;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PA = (TextView) findViewById(R.id.PA);
Interest_Rate = (TextView) findViewById(R.id.Interest_Rate);
Years = (TextView) findViewById(R.id.Years);
PA_bar = (EditText) findViewById(R.id.PA_bar);
IR_bar = (EditText) findViewById(R.id.IR_bar);
year_bar = (EditText) findViewById(R.id.year_bar);
calculate = (Button) findViewById(R.id.calculate);
t1 = (TextView) findViewById(R.id.t1);
calculate.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
int num1 = Integer.parseInt(PA_bar.getText().toString());
int num2 = Integer.parseInt(IR_bar.getText().toString());
int num = Integer.parseInt(year_bar.getText().toString());
int si = (num1 * num2 * num) / 100;
t1.setText(Integer.toString(si));
}
});
}};
You have a syntactical error in your code. You are missing the closing parentheses and semi-colon.
calculate.setOnClickListener(new OnClickListener() {
public void onClick(View v){
}
}); //<--- Change is here.

Categories

Resources