I am building a BMR calculator with radio buttons for Male and Female.
I am using a switch case to calculate BMR for each but it doesn't seem to work.
Nothing happens when I press the calculate button.
It seems to work okay when I calculate it directly i.e without switch case, the ResultTextView becomes visible and shows the answers. I apologize if I am repeating the question, I am new to programming. Please ignore the formulae for BMR I know they aren't correct I just put them for testing.
Following is my code:
import androidx.appcompat.app.AppCompatActivity;
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.TextView;
import android.widget.Toast;
public class BmrActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton bmrFemaleRadioButton;
RadioButton bmrMaleRadioButton;
EditText bmrAgeEditText;
EditText bmrWeightEditText;
EditText bmrHeightEditText;
Button bmrCalculateButton;
TextView bmrResultTextView;
Double age;
Double weight;
Double height;
Double resultBmr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmr);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
bmrFemaleRadioButton = findViewById(R.id.bmrFemaleRadioButton);
bmrMaleRadioButton = findViewById(R.id.bmrMaleRadioButton);
bmrAgeEditText = findViewById(R.id.bmrAgeEditText);
bmrWeightEditText = findViewById(R.id.bmrWeightEditText);
bmrHeightEditText = findViewById(R.id.bmrHeightEditText);
bmrCalculateButton = findViewById(R.id.bmrCalculateButton);
bmrResultTextView = findViewById(R.id.bmrResultTextView);
bmrFemaleRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bmrAgeEditText.setVisibility(View.VISIBLE);
bmrWeightEditText.setVisibility(View.VISIBLE);
bmrHeightEditText.setVisibility(View.VISIBLE);
bmrCalculateButton.setVisibility(View.VISIBLE);
}
});
bmrMaleRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bmrAgeEditText.setVisibility(View.VISIBLE);
bmrWeightEditText.setVisibility(View.VISIBLE);
bmrHeightEditText.setVisibility(View.VISIBLE);
bmrCalculateButton.setVisibility(View.VISIBLE);
}
});
}
public void calculateBmr(final View view){
age = Double.parseDouble(bmrAgeEditText.getText().toString());
weight = Double.parseDouble(bmrWeightEditText.getText().toString());
height = Double.parseDouble(bmrHeightEditText.getText().toString());
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.bmrFemaleRadioButton:
resultBmr = age + weight + height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
case R.id.bmrMaleRadioButton:
resultBmr = age * weight * height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
}
}
});
}
}
Following is my XML layout file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".BmrActivity">
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="#+id/bmrFemaleRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:text="Female" />
<RadioButton
android:id="#+id/bmrMaleRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:text="Male" />
</RadioGroup>
<EditText
android:id="#+id/bmrAgeEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Enter your age"
android:inputType="number"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/radioGroup" />
<EditText
android:id="#+id/bmrWeightEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:hint="Enter your weight in kgs"
android:inputType="number"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrAgeEditText" />
<EditText
android:id="#+id/bmrHeightEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:hint="Enter your height in cms"
android:inputType="number"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrWeightEditText" />
<Button
android:id="#+id/bmrCalculateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:onClick="calculateBmr"
android:text="Calculate"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrHeightEditText" />
<TextView
android:id="#+id/bmrResultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="monospace"
android:text="Answer"
android:textAlignment="center"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrCalculateButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
You are doing it wrong. You are calling setOnCheckedChangeListener() when the button has been clicked, but by that time the radio button has already been checked. The onCheckedChange() is called when the change occurs.
Instead of setting a listener, you can directly get the checked item id by calling radioGroup.getCheckedRadioButtonId()
like this
switch(radioGroup.getCheckedRadioButtonId()){
case R.id.bmrFemaleRadioButton:
resultBmr = age + weight + height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
case R.id.bmrMaleRadioButton:
resultBmr = age * weight * height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
}
Did you try move get age, weight, height inside onCheckChanged. Because it only parse one time and not update again.
Related
I wanted to create an android app that adds two number.
Firstly i set up the Layout design.
Secondly in the main_activity file i wrote the code.
This is my code:
package com.example.asus.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
double num1,num2, sum;
EditText firstNumber;
EditText secondNumber;
TextView addResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
//TextView addResult;
Button btnAdd;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstNumber = (EditText)findViewById(R.id.editText);
secondNumber = (EditText)findViewById(R.id.editText2);
addResult = (TextView)findViewById(R.id.textView4);
btnAdd = (Button)findViewById(R.id.button);
//Button button = (Button)findViewById(R.id.button);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num1 = Double.parseDouble(firstNumber.getText().toString());
//num1 = Double.parseDouble(firstNumber.getText().toString());
num2 = Double.parseDouble(secondNumber.getText().toString());
//num2 = Double.parseDouble(secondNumber.getText().toString());
sum = num1 + num2;
//sum = num1 + num2;
addResult.setText(Double.toString(sum));
// addResult.setText(Double.toString(sum));
}
});
}
}
my code has no errors, however when i run the android emulator it doesn't take any input.
when i click on letter or number, the cursor moves a step, but no input is shown.
I have tried those solutions that i have found, but none has worked for me:
From advanced settings, check enable keyboard input.
From AVD, create a virtual device, hardware profile, check has hardware keyboard input.
Add in config file hw.keyboard=yes
However none of them worked for me, where is the error exactly?
This is my Layout file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="25dp"
android:layout_marginLeft="25dp"
android:text="First Number"
app:layout_constraintBottom_toBottomOf="#+id/editText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/editText" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="25dp"
android:layout_marginLeft="25dp"
android:text="Second Number:"
app:layout_constraintBottom_toBottomOf="#+id/editText2"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="33dp"
android:layout_marginLeft="33dp"
android:text="Result:"
app:layout_constraintBottom_toBottomOf="#+id/editText3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/editText3" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="21dp"
android:layout_marginTop="103dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="21dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="21dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="87dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="41dp"
android:text="ADD"
app:layout_constraintStart_toEndOf="#+id/textView2"
app:layout_constraintTop_toBottomOf="#+id/editText2" />
</android.support.constraint.ConstraintLayout>
show your XML code , it might be :
1- you set a custom input type for Edit Text;
2- your windows/Ubuntu/mac is on a unsupported keyboard language for emulator;
3- in emulator advanced settings keyboard input is disabled ;
The height of the EditText are too small to display the text. So increase the height of those views or change it into wrap_content.
I have the following code but it changes the button text to empty. I'm basically trying to change the the button's text when it clicked to whatever the user types into the edit text field I have. Everything seems to work, however, when I click on either buttons I have the button's text changes to empty/null and since i'm using wrap content it shrinks the size of the button too.
activity_main.xml
<LinearLayout
android:layout_width="368dp"
android:layout_height="495dp"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000ff"
android:gravity="center"
android:padding="10dp"
android:text="Name: Balkar Rana"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:textColor="#FFFF00"
android:textSize="20dp"
android:textStyle="bold"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:textColor="#FF69B4"
android:text="Username: "
android:textSize="20dp"/>
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#000000"
android:textSize="20dp"
android:id="#+id/username"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:textColor="#63ea1f"
android:text="Password: "
android:textSize="20dp"/>
<EditText
android:inputType="textPassword"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#000000"
android:textSize="20dp"
android:id="#+id/password"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="25dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:text="Username"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#FF69B4"
android:id="#+id/userButton"
android:onClick="onClick"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="10dp"
android:text="Password"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#63ea1f"
android:id="#+id/passButton"
android:onClick="onClick"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="10dp"
android:text="USER-PASS"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#FF69B4"
android:id="#+id/userPassButton"
android:onClick="onClick"/>
</LinearLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
MainActivity.java
package com.example.balkarrana.lab2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText usernameInput = (EditText)findViewById(R.id.username);
final String userText = usernameInput.getText().toString();
final Button userButtonVariable = (Button)findViewById(R.id.userButton);
EditText passwordInput = (EditText)findViewById(R.id.username);
final String passText = passwordInput.getText().toString();
final Button passButtonVariable = (Button)findViewById(R.id.passButton);
final String userPassText = userText + passText;
final Button userPassButtonVariable = (Button)findViewById(R.id.userPassButton);
userButtonVariable.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
userButtonVariable.setText(userText);
}
});
passButtonVariable.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
passButtonVariable.setText(passText);
}
});
userPassButtonVariable.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
userPassButtonVariable.setText(userPassText);
}
});
}
}
You are getting the value of the EditText within your onCreate when the app is first started and they will be blank. You need to get the current value within the onClick and then set it. Here's how I'd do it for the userButton.
...
public class MainActivity extends AppCompatActivity{
EditText usernameInput;
Button userButtonVariable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameInput = (EditText)findViewById(R.id.username);
userButtonVariable = (Button)findViewById(R.id.userButton);
userButtonVariable.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String userText = usernameInput.getText().toString();
userButtonVariable.setText(userText);
}
});
To stop a button changing size don't set the width to be wrap_content.
Try match_parent and then use margins.
<Button
android:layout_width="match_parent"
...
</Button>
I'm trying to make a page that has a list view in android, and then when you click on one of the items in the list, it should lead to a new activity, with a specific format.
Basically, it's a grades centre page, with a list of your courses, when you click on a course it should open to a course page.
I have created a Grades centre activity, a single course page activity and their respective classes.
Right now the 2 pages exist but they aren't linked to each other, This is actually a huge file with many other pages etc, but I just posted the part I need help with but if necessary I can post the others as well. I want the elements in the list to be clickable - and then lead to the course page that the user clicked on, like one of the courses is Biol 116 then the list should take you to the biol 116 course page. Thanks in advance for all the help! :)
GradeCentre 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_grades_centre"
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.gregmallan.yuboard.GradesCentre"><![CDATA[
android:clickable="true">
]]>
<TextView
android:text="Current Overall Grade:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="21dp" />
<ListView
android:id="#+id/CourseGradeList"
android:layout_height="350dp"
android:layout_width="230dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="25dp" />
<TextView
android:text="85.67"
android:layout_height="40dp"
android:id="#+id/Overall"
android:layout_width="80dp"
android:textSize="25sp"
android:textColor="#android:color/holo_red_light"
android:layout_alignTop="#+id/textView3"
android:layout_toEndOf="#+id/CourseGradeList"
android:layout_marginStart="17dp" />
GradeCentre java file:
public class GradesCentre extends AppCompatActivity {
double OverallAvg;
ArrayList<Course> AllCourses;
ArrayAdapter<Course> AdapterCourse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grades_centre);
AllCourses = new ArrayList<>();
AllCourses.add(new Course("Cosc 111"));
AllCourses.add(new Course("Biol 116"));
AllCourses.add(new Course("Anth 100"));
AllCourses.get(0).setCourseGrade(95);
AllCourses.get(1).setCourseGrade(78);
AllCourses.get(2).setCourseGrade(84);
OverallAvg = calcOverallGrade(AllCourses);
AdapterCourse = new ArrayAdapter<Course>(this , android.R.layout.simple_list_item_1 , AllCourses);
ListView listView = (ListView) findViewById(R.id.CourseGradeList);
listView.setAdapter(AdapterCourse);
}
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
}
public double calcOverallGrade(ArrayList<Course> Anything){
double sum = 0;
for(int i = 0; i < Anything.size();i++ ){
sum = Anything.get(i).getCourseGrade() + sum;
}
OverallAvg = sum/(Anything.size());
return OverallAvg;
}
}
Single Course Page xml:
<TextView
android:text="_________________________________________________"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:id="#+id/textView10"
android:textStyle="normal|bold"
android:textColor="#color/colorPrimaryDark"
android:layout_below="#+id/SingleCourseGrade"
android:layout_alignParentStart="true" />
<TextView
android:text="_________________________________________________"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:id="#+id/textView9"
android:textStyle="normal|bold"
android:textColor="#color/colorPrimaryDark"
android:layout_below="#+id/SingleCourseGrade"
android:layout_alignParentStart="true" />
<TextView
android:text="ex. Course 1"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/CourseName"
android:layout_height="30dp"
android:layout_width="200dp"
android:textSize="24sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="normal|bold" />
<TextView
android:text="Current Overall Grade: "
android:layout_height="30dp"
android:layout_below="#+id/CourseName"
android:layout_alignParentStart="true"
android:layout_marginTop="15dp"
android:id="#+id/textView5"
android:textSize="20sp"
android:textColor="#color/colorPrimaryDark"
android:layout_width="200dp" />
<Button
android:text="Add/Manage Components"
android:layout_height="50dp"
android:id="#+id/AddManage"
android:layout_width="350dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
<ListView
android:id="#+id/SingleCourseGradeList"
android:layout_above="#+id/AddManage"
android:layout_alignStart="#+id/AddManage"
android:layout_height="315dp"
android:layout_width="280dp" />
<TextView
android:text="%%%"
android:layout_marginEnd="14dp"
android:id="#+id/SingleCourseGrade"
android:textSize="20sp"
android:textColor="#android:color/holo_red_light"
android:layout_alignParentEnd="true"
android:layout_width="60dp"
android:layout_height="25dp"
android:layout_alignTop="#+id/textView5" />
<TextView
android:text="_________________________________________________"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:id="#+id/textView8"
android:textStyle="normal|bold"
android:textColor="#color/colorPrimaryDark"
android:layout_above="#+id/textView5"
android:layout_alignParentStart="true" />
<TextView
android:text="Individual Components and Grades:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView7"
android:textSize="16sp"
android:textColor="#color/colorPrimaryDark"
android:layout_above="#+id/SingleCourseGradeList"
android:layout_alignStart="#+id/SingleCourseGradeList" />
</RelativeLayout>
Single course page java file:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.gregmallan.yuboard.SchoolRelatedClasses.CourseComponent;
import java.util.ArrayList;
public class SingleCoursePage extends AppCompatActivity{
ArrayAdapter<CourseComponent> adapter;
Button Components;
Button CompDetail;
double CourseGrade;
ArrayList<CourseComponent> AllComponents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_course_page);
//this is just added until we get real data
AllComponents = new ArrayList<CourseComponent>();
CourseComponent x = new CourseComponent("Dummy", 20);
AllComponents.add(x);
CourseComponent x2 = new CourseComponent("Dummy2", 40);
AllComponents.add(x2);
adapter = new ArrayAdapter<CourseComponent>(this , android.R.layout.simple_list_item_1 , AllComponents);
ListView listView = (ListView) findViewById(R.id.SingleCourseGradeList);
listView.setAdapter(adapter);
Components = (Button) findViewById(R.id.AddManage);
Components.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//Inform the user the button has been clicked
openCourseComponents(v);
}
});
}
public void openCourseComponents(View view){
Intent intent1 = new Intent(this, IndividualCourseCentre.class);
startActivity(intent1);
}
//public void openComponentBreakdown(View view){
// Intent intent2 = new Intent(this, IndividualCourseCentre.class);
// startActivity(intent2);
//}
public double calcCourseGrade(ArrayList<CourseComponent> x){
double sum = 0;
for(int i = 0; i < x.size();i++){
sum = x.get(i).getTotalComponentGrade();
}
CourseGrade = sum/(x.size());
return CourseGrade;
//TO-DO
//when this method is called changed the text to the CourseGrade
}
}
You can use the following code:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String selectedFromList =(String) (listView.getItemAtPosition(position));
Intent intent = new Intent(GradesCentre.this, Cosc111Activity.class);
if(selectedFromList.equals("Cosc 111")){
//Set object here
intent.putExtra("Course_Details", obj);
startActivity(intent);
}
else if(selectedFromList.equals("Biol 116")){
//Set object here
intent.putExtra("Course_Details", obj);
startActivity(intent);
}
//Do as above for rest of the list items
}
});
Get the object in SingleCourseActivity like this:
getIntent().getSerializableExtra("Course_Details");
Hope this helps.
My method that is called (calculate BMI) inside of my activity is supposed to compute and display BMI (based on the formula inside the code), and display its value inside of a textview. The application runs correctly, however the value displayed is always zero. I am struggling to figure out if the problem lies in my formula (unlikely) or if the way that I am passing the value is incorrect. Any help would be appreciated. Code below
.Java file
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import android.widget.Toast;
public class Health extends ActionBarActivity {
EditText bloodPressure;
EditText cholesterol;
int weight;
int height;
EditText heightString;
EditText age;
TextView bmiText;
EditText weightString;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health);
weightString = (EditText) findViewById(R.id.weightTextBox);
heightString =(EditText) findViewById(R.id.heightTextBox);
bmiText = (TextView) findViewById(R.id.bmiTextView);
bloodPressure = (EditText) findViewById(R.id.bloodPressureTextBox);
cholesterol = (EditText) findViewById(R.id.cholesterolTextBox);
age = (EditText) findViewById(R.id.ageTextBox);
dbHandler = new MyDBHandler(this, null, null, 1);
}
public void calculateBMI(View view)
{
weight = Integer.parseInt(weightString.getText().toString());
height = Integer.parseInt(heightString.getText().toString());
int BMI = 703 * (weight/(height*height));
bmiText.setText("Your calculated BMI is: " + Integer.toString(BMI));
Toast.makeText(Health.this, " Info Saved ", Toast.LENGTH_SHORT).show();
HealthInfo healthInfo = new HealthInfo(bloodPressure.getText().toString(),cholesterol.getText().toString(),heightString.getText().toString(),weightString.getText().toString(),age.getText().toString());
dbHandler.addHealth(healthInfo);
}
public void calorieClick(View view){
Intent i = new Intent(this, CalorieTracker.class);
startActivity(i);
}
public void openTips(View view){
Intent i = new Intent(this, HealthTipsActivity.class);
startActivity(i);
}
public void openPlans(View view){
Intent i = new Intent(this, DietPlansActivity.class);
startActivity(i);
}
#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_health, 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);
}
}
.XML file
<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="seniorproject.broncos.broncowellnessapp.Health"
android:background="#006699">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/blood_pressure_text"
android:id="#+id/bloodPressureTextView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/cholesterol_text"
android:id="#+id/cholesterolTextView"
android:layout_below="#+id/bloodPressureTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/weight_text"
android:id="#+id/weightTextView"
android:layout_below="#+id/cholesterolTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/height_text"
android:id="#+id/heightTextView"
android:layout_below="#+id/weightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/age_text"
android:id="#+id/ageTextView"
android:layout_below="#+id/heightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="35dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10"
android:width="150dp"
android:id="#+id/bloodPressureTextBox"
android:layout_below="#+id/bloodPressureTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/cholesterolTextBox"
android:layout_below="#+id/cholesterolTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/weightTextBox"
android:layout_below="#+id/weightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/heightTextBox"
android:layout_below="#+id/heightTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:width="150dp"
android:id="#+id/ageTextBox"
android:layout_below="#+id/ageTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/diet_plans_button_text"
android:onClick="openPlans"
android:id="#+id/dietPlansButton"
android:layout_below="#+id/ageTextBox"
android:layout_marginTop="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/calorie_tracker_button"
android:id="#+id/calorieAccessButton"
android:layout_below="#+id/dietPlansButton"
android:onClick ="calorieClick"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/tips_button_text"
android:id="#+id/tipsButton"
android:onClick="openTips"
android:layout_below="#+id/calorieAccessButton"
android:layout_alignRight="#+id/calorieAccessButton"
android:layout_alignEnd="#+id/calorieAccessButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/BMI_button_text"
android:id="#+id/bmiButton"
android:onClick="calculateBMI"
android:layout_alignBottom="#+id/cholesterolTextBox"
android:layout_alignRight="#+id/dietPlansButton"
android:layout_alignEnd="#+id/dietPlansButton"
android:layout_marginRight="36dp"
android:layout_marginEnd="36dp"
android:background="#ff00b812" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Push Button to Compute BMI"
android:id="#+id/bmiTextView"
android:layout_alignBottom="#+id/weightTextBox"
android:layout_alignLeft="#+id/bmiButton"
android:layout_alignStart="#+id/bmiButton" />
</RelativeLayout>
Your weight and height variables are int. That is your problem. Change them to float or double
Currently, you are doing integer division which is causing the result to be truncated as follows: 1 / 2 gives 0
You are doing a division for integer which results mostly to zero.
That is why the result is always zero.
Change your weight and height variables to double like this
and just cast the result back to int.
double weight = 0.0;
double height = 0.0;
int BMI = (int)(703 * (weight/(height*height)));
bmiText.setText("Your calculated BMI is: " + Integer.toString(BMI));
Place this on the end of the onCreate() method:
findViewById(R.id.bmiButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
weight = Integer.parseInt(weightString.getText().toString());
height = Integer.parseInt(heightString.getText().toString());
int BMI = 703 * (weight/(height*height));
bmiText.setText("Your calculated BMI is: " + Integer.toString(BMI));
Toast.makeText(Health.this, " Info Saved ", Toast.LENGTH_SHORT).show();
HealthInfo healthInfo = new HealthInfo(bloodPressure.getText().toString(),cholesterol.getText().toString(),heightString.getText().toString(),weightString.getText().toString(),age.getText().toString());
dbHandler.addHealth(healthInfo);
}
});
Some android version does not support onClick attribute for Button tag in XAML.
I am new to Android development and I have an issue with making Android EditText vertically scroll able. The vertical scrolling of the EditText does not work for me. I followed several posts and resources but none of them worked for me.
I am using the following code sample to enable the vertical scroll ability.
this.detailsEditText.setScroller(new Scroller(this));
this.detailsEditText.setMaxLines(1);
this.detailsEditText.setVerticalScrollBarEnabled(true);
this.detailsEditText.setMovementMethod(new ScrollingMovementMethod());
The following are the activity class and layout resource file, respectively I am using in my app.
CreateAppointmentActivity.java
package lk.iit.appointmentmanagerapp.activities;
import java.sql.Date;
import java.sql.Time;
import lk.iit.appointmentmanagerapp.data.Appointment;
import lk.iit.appointmentmanagerapp.data.DatabaseHandler;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Scroller;
public class CreateAppointmentActivity extends Activity {
private EditText titleEditText;
private EditText timeEditText;
private EditText detailsEditText;
private EditText dateEditText;
private Button saveButton;
private Button resetButton;
private final DatabaseHandler handler = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_appointment);
this.titleEditText = (EditText)(this.findViewById(R.id.edit_title));
this.timeEditText = (EditText)(this.findViewById(R.id.edit_time));
this.detailsEditText = (EditText)(this.findViewById(R.id.edit_details));
this.dateEditText = (EditText)(this.findViewById(R.id.edit_date));
this.detailsEditText.setScroller(new Scroller(this));
this.detailsEditText.setMaxLines(1);
this.detailsEditText.setVerticalScrollBarEnabled(true);
this.detailsEditText.setMovementMethod(new ScrollingMovementMethod());
SharedPreferences preferences = getSharedPreferences("date_variables", MODE_PRIVATE);
this.dateEditText.setText(preferences.getInt("Year", 0) + "-" + preferences.getInt("Month", 0) + "-" + preferences.getInt("Day", 0));
this.dateEditText.setEnabled(false);
this.saveButton = (Button)(this.findViewById(R.id.save_new_appointment_button));
this.saveButton.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
String[] dateComponents = dateEditText.getText().toString().split("-");
String[] timeComponents = timeEditText.getText().toString().split(":");
Appointment appointment = new Appointment();
appointment.setAppointment_title(titleEditText.getText().toString());
appointment.setAppointment_date(new Date(Integer.parseInt(dateComponents[0]), Integer.parseInt(dateComponents[1]), Integer.parseInt(dateComponents[2])));
appointment.setAppointment_time(new Time(Integer.parseInt(timeComponents[0]), Integer.parseInt(timeComponents[1]), Integer.parseInt(timeComponents[2])));
appointment.setAppointment_details(detailsEditText.getText().toString());
boolean inserted = handler.addAppointment(appointment);
//
//
}
});
this.resetButton = (Button)(this.findViewById(R.id.reset_button));
this.resetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
titleEditText.setText("");
timeEditText.setText("");
detailsEditText.setText("");
dateEditText.setText("");
}
});
}
}
activity_create_appointment.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"
android:background="#color/background"
tools:context="lk.iit.appointmentmanagerapp.activities.CreateAppointmentActivity" >
<TextView
android:id="#+id/create_activity_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome_create"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dip"
android:layout_marginBottom="25dip"
android:textSize="18.5sp"
android:textColor="#ffffff" />
<TextView
android:id="#+id/title_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/create_activity_title"
android:layout_marginTop="15dip"
android:text="#string/title_textview_text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/edit_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/create_activity_title"
android:layout_marginTop="15dip"
android:layout_toRightOf="#+id/title_textview"
android:layout_marginLeft="30dip"
android:background="#ffffff"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/time_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title_textview"
android:layout_marginTop="25dip"
android:text="#string/time_textview_text"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<EditText
android:id="#+id/edit_time"
android:background="#ffffff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/time_textview"
android:layout_below="#+id/edit_title"
android:layout_marginLeft="25dip"
android:layout_marginTop="25dip"
android:ems="10"
android:inputType="time" />
<TextView
android:id="#+id/details_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/time_textview"
android:text="#string/details_textview_text"
android:layout_marginTop="25dip"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/edit_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/details_textview"
android:layout_alignBottom="#+id/details_textview"
android:layout_alignLeft="#+id/edit_title"
android:background="#ffffff"
android:ems="10"
android:inputType="text" >
</EditText>
<TextView
android:id="#+id/date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/details_textview"
android:text="Date"
android:layout_marginTop="25dip"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/edit_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/date_textview"
android:layout_below="#+id/edit_details"
android:background="#ffffff"
android:layout_marginLeft="25dip"
android:layout_marginTop="25dip"
android:ems="10"
android:inputType="date" >
</EditText>
<Button
android:id="#+id/save_new_appointment_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/date_textview"
android:layout_marginTop="15dip"
android:layout_marginBottom="10dip"
android:layout_centerHorizontal="true"
android:text="#string/save_button_text"
android:textAllCaps="false" />
<Button
android:id="#+id/reset_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/save_new_appointment_button"
android:layout_marginTop="2dip"
android:layout_centerHorizontal="true"
android:text="#string/reset_button_text"
android:textAllCaps="false" />
</RelativeLayout>
Please bear with me if I have done any mistakes as I am relatively new to this area of development.
I would be grateful if someone help me out with this issue.
Try this in java code:
EditText dwEdit = (EditText) findViewById(R.id.DwEdit);
dwEdit.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
// TODO Auto-generated method stub
if (view.getId() ==R.id.DwEdit) {
view.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction()&MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_UP:
view.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
}
return false;
}
});
And in your xml:
<EditText
android:id="#+id/DwEdit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minLines="10"
android:scrollbarStyle="insideInset"
android:scrollbars="vertical"
android:overScrollMode="always"
android:inputType="textCapSentences">
</EditText>
If you wanna scroll editText only in detailEditText then you specify height of editText 50dp or your need and remove inputType="text" from your editText ....it fulfill your need..
and you don't need any code in java relative to that editText..