String from EditText to Float error - java

I'm trying to convert a string to a float.
Basically, I have an edittext that's numerical only, and I'm trying to get the input of it and do some math with it before outputting the result onto another edittext.
Here is my main activity.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//Declare views
EditText ptv = (EditText) findViewById(R.id.priceet);
EditText ttv = (EditText) findViewById(R.id.taxet);
EditText totaltv = (EditText) findViewById(R.id.totalet);
//Declare variables
float price = 0;
price = Float.valueOf(ptv.getText().toString());
float tax = 0.0F;
tax = Float.valueOf(ttv.getText().toString()) / 100;
float total = price*tax + price;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
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: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=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:listSeparatorTextViewStyle"
android:text="Price"
android:id="#+id/cost"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/priceet" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/priceet"
android:layout_below="#+id/cost"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:listSeparatorTextViewStyle"
android:text="Tax %"
android:id="#+id/taxtv"
android:layout_below="#+id/priceet"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/taxet"
android:layout_below="#+id/taxtv"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/totalet" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:listSeparatorTextViewStyle"
android:text="Total"
android:id="#+id/totaltv"
android:layout_below="#+id/taxet"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/totalet"
android:layout_below="#+id/totaltv"
android:layout_alignParentStart="true"
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_alignEnd="#+id/cost" />
and here is the error I'm getting
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jimlarck.taxcalculator/com.jimlarck.taxcalculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
The error points to this line of code:
price = Float.valueOf(ptv.getText().toString());
How would I fix this? I read somewhere around here that this error is thrown when something isn't initialized properly but everything looks fine on my end. Any help is appreciated. Thank you :)

You need to instantiate your EditTexts after you call super.onCreate() and setContentView():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Declare views
EditText ptv = (EditText) findViewById(R.id.priceet);
EditText ttv = (EditText) findViewById(R.id.taxet);
EditText totaltv = (EditText) findViewById(R.id.totalet);
//Declare variables
float price = 0;
price = Float.valueOf(ptv.getText().toString());
float tax = 0.0F;
tax = Float.valueOf(ttv.getText().toString()) / 100;
float total = price*tax + price;
}

Related

Rectangle Area Calculation

I am trying to calculate the rectangle area in my application. I have created a simple layout but for some reason, data is not parsed into the application. I tried to print it in the console but nothing is shown.
This is my Main Class:
package com.example.week3labcode;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button calcButton;
EditText number1, number2, resultFinal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calcButton = (Button)findViewById(R.id.button1);
number1 = (EditText) findViewById(R.id.edtext1);
number2 = (EditText) findViewById(R.id.edtext2);
resultFinal = (EditText) findViewById(R.id.edtext3);
}
#Override
public void onClick(View v){
if(v == calcButton){
number1 = (EditText) findViewById(R.id.edtext1);
number2 = (EditText) findViewById(R.id.edtext2);
double num1 = Double.parseDouble(number1.getText().toString());
double num2 = Double.parseDouble(number2.getText().toString());
calcRectangle(num1, num2);
}
}
public void calcRectangle(double x, double y){
double result = x * y;
System.out.println(result);
resultFinal = (EditText) findViewById(R.id.edtext3);
resultFinal.setText(Double.toString(result));
System.out.println('H' + result);
}
}
And the following code in my XML file that provides layout for the application:
<?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=".MainActivity">
<TextView
android:id="#+id/label1"
android:layout_centerHorizontal="true"
android:layout_marginVertical="20px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rectangle Area Calculation" />
<TextView
android:id="#+id/label2"
android:layout_below="#+id/label1"
android:layout_centerHorizontal="true"
android:layout_marginVertical="10px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Length" />
<EditText
android:id="#+id/edtext1"
android:layout_toRightOf="#+id/label2"
android:layout_centerHorizontal="true"
android:layout_alignBaseline="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/label3"
android:layout_below="#+id/label2"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter breadth" />
<EditText
android:id="#+id/edtext2"
android:layout_toRightOf="#+id/label3"
android:layout_alignBaseline="#+id/label3"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/button1"
android:layout_below="#+id/label3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate" />
<TextView
android:id="#+id/label4"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginVertical="20px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Area in cm2" />
<EditText
android:id="#+id/edtext3"
android:layout_toRightOf="#+id/label4"
android:layout_centerHorizontal="true"
android:layout_alignBaseline="#+id/label4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/button2"
android:layout_below="#+id/label4"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Entries" />
</RelativeLayout>
You have not set OnClickListener to your Button so calcRectangle() method is never called.
calcButton = (Button)findViewById(R.id.button1);
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
number1 = (EditText) findViewById(R.id.edtext1);
number2 = (EditText) findViewById(R.id.edtext2);
double num1 = Double.parseDouble(number1.getText().toString());
double num2 = Double.parseDouble(number2.getText().toString());
calcRectangle(num1, num2);
}
});
OR
calcButton.setOnClickListener(this);

Android Studio Counter TextView Field not updating

Assuming Imports and Stuff
Im trying to build a simple Calorie Counter, but having a trouble displaying
the number of calories. I also want it to add to the previous input..
for instance if the user enters 500, 400, 300 the total in the TextField
should be 1200.
activity_main.xml
<?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:id="#+id/CalorieAdd"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="rav_singh.caloriecounter.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="Current Calories "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/caloriesNeeded"
android:textSize="30dp"
android:layout_marginTop="41dp"
android:layout_marginEnd="69dp"
android:layout_below="#+id/calCount"
android:layout_alignParentEnd="true" />
<TextView
android:text="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/calCount"
android:textAlignment="center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="40dp" />
<Button
android:text="Add "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/calorieAdd"
android:layout_marginTop="88dp"
android:layout_below="#+id/caloriesNeeded"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/calorieinput"
android:hint="Add Calories "
android:layout_marginTop="12dp"
android:layout_below="#+id/caloriesNeeded"
android:layout_alignStart="#+id/caloriesNeeded"
android:textAlignment="center" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity
{
EditText input;
TextView calTotal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calTotal = (TextView) findViewById(R.id.calCount);
input = (EditText) findViewById(R.id.calorieinput);
Button calorieAdd = (Button) findViewById(R.id.calorieAdd);
calTotal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Float n1 = Float.valueOf(input.getText().toString());
calTotal.setText(Float.toString(n1));
}
});
}
}
previous input.. for instance if the user enters 500, 400, 300 the
total in the TextField should be 1200
Add both TextView and EditText data before updating counter in TextView like:
#Override
public void onClick(View view) {
float n0 = Float.parseFloat(calTotal.getText().toString());
float n1 = Float.parseFloat(input.getText().toString());
calTotal.setText(Float.toString(n0+n1));
}
Also added empty check for EditText before parsing value to Float to avoid NumberFormatException Exception.
try
if(input.getText().toString().trim().length() > 0)
float n1 = Float.parseFloat(input.getText().toString());
instead of:
Float n1 = Float.valueOf(input.getText().toString());

I created this but the function keeps having errors? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Basically, I'm trying to make this eating healthy app based on their BMI. The calculator is done but now I'm stuck at this where the user clicks on one of these 3 buttons and that list in the Spinner item and the ImageView changes accordingly (if user clicks breakfast button, then the spinner list and image change to breakfast and so). Even the image is not working. The app runs but when I click the button it terminates and I don't know how to fix it. if it's possible, can you guys also let me know the way I'm doing my Spinner will work or not?
MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button Toch;
Button BTbtn;
Button LunchBtn;
Button DinnerBtn;
Button Submit;
EditText inweight;
EditText inheight;
EditText inage;
TextView BMR;
RadioButton rdM;
RadioButton rdF;
ImageView maimage;
Spinner spinner;
/**
Button Submit = (Butt
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button Submit = (Button)findViewById(R.id.Sumbit);
final Button Toch = (Button) findViewById(R.id.Toch);
Toch.setOnClickListener(this);
final Button BTbtn = (Button) findViewById(R.id.BTbtn);
BTbtn.setOnClickListener(this);
final Button LunchBtn = (Button) findViewById(R.id.LunchBtn);
LunchBtn.setOnClickListener(this);
final Button DinnerBtn = (Button) findViewById(R.id.DinnerBtn);
DinnerBtn.setOnClickListener(this);
//EditText
final EditText inweight = (EditText) findViewById(R.id.inweight);
final EditText inheight = (EditText) findViewById(R.id.inheight);
final EditText inage = (EditText) findViewById(R.id.inage);
//Text View
final TextView BMR = (TextView) findViewById(R.id.BMR);
// final TextView FDName=(TextView)findViewById(R.id.FDName);
//RadioButton
final RadioButton rdM = (RadioButton) findViewById(R.id.rdM);
final RadioButton rdF = (RadioButton) findViewById(R.id.rdF);
//ImageView
final ImageView maimage = (ImageView) findViewById(R.id.maimage);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.BTbtn: {
maimage.setImageResource(R.drawable.breakfast);
//ArrayAdapter bList = ArrayAdapter.createFromResource(getApplicationContext(), android.R.array.breakfastList, android.R.layout.simple_dropdown_item_1line);
}
case R.id.LunchBtn: {
maimage.setImageResource(R.drawable.dinner);
//ArrayAdapter lList = ArrayAdapter.createFromResource(getApplicationContext(), android.R.array.lunchList, android.R.layout.simple_dropdown_item_1line);
}
case R.id.DinnerBtn: {
maimage.setImageResource(R.drawable.lunch);
//ArrayAdapter dList = ArrayAdapter.createFromResource(getApplicationContext(), android.R.array.dinnerList, android.R.layout.simple_dropdown_item_1line);
}
case R.id.Sumbit: {
double weight = Double.parseDouble(inweight.getText().toString());
double height = Double.parseDouble(inheight.getText().toString());
double age = Double.parseDouble(inage.getText().toString());
double gender;
if (rdM.isChecked()) {
gender = 66;
double ans = gender + (13.7 * weight) + (5 * height) - (6.8 * age);
BMR.setText("" + (int) ans);
}
if (rdF.isChecked()) {
gender = 655;
double ans = gender + (9.6 * weight) + (1.8 * height) - (4.7 * age);
BMR.setText("Your Calories require : " + (int) ans);
}
}
case R.id.Toch: {
inweight.setHint(R.string.chweight);
inheight.setHint(R.string.chhight);
inage.setHint(R.string.chage);
}
}
}
}
R.layout.activity_main:
<?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: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.cmleu_000.myapplication.MainActivity">
<TextView
android:text="Food Name:"
android:textSize="18dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView" />
<Button
android:id="#+id/BTbtn"
android:text="Breakfast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/LunchBtn"
android:layout_alignRight="#+id/radioGroup2"
android:layout_alignEnd="#+id/radioGroup2" />
<Button
android:id="#+id/LunchBtn"
android:text="Lunch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/DinnerBtn"
android:layout_alignRight="#+id/BTbtn"
android:layout_alignEnd="#+id/BTbtn" />
<Button
android:id="#+id/DinnerBtn"
android:text="Dinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/maimage"
android:layout_alignLeft="#+id/LunchBtn"
android:layout_alignStart="#+id/LunchBtn" />
<ImageView
android:id="#+id/maimage"
android:src="#drawable/dinner"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_above="#+id/qweight"
android:layout_alignLeft="#+id/qhight"
android:layout_alignStart="#+id/qhight" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Sumbit"
android:layout_alignRight="#+id/Sumbit"
android:layout_alignEnd="#+id/Sumbit"
android:id="#+id/radioGroup2">
<RadioButton
android:id="#+id/rdF"
android:text="F"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/rdM"
android:layout_toRightOf="#+id/rdM"
android:layout_toEndOf="#+id/rdM"
android:layout_gravity="left" />
<RadioButton
android:id="#+id/rdM"
android:text="M"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/radioGroup"
android:layout_toRightOf="#+id/qage"
android:layout_toEndOf="#+id/qage"
android:layout_gravity="left" />
</RadioGroup>
<TextView
android:text="Your weight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/qweight"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/inweight"
android:hint="Plase input your weight (KG)"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/qhight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:text="Your height"
android:id="#+id/qhight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/inheight"
android:layout_alignRight="#+id/qweight"
android:layout_alignEnd="#+id/qweight" />
<EditText
android:id="#+id/inheight"
android:hint="Please input your height (CM)"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/qage"
android:layout_alignRight="#+id/inweight"
android:layout_alignEnd="#+id/inweight" />
<TextView
android:text="Your age"
android:id="#+id/qage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/inage"
android:layout_alignLeft="#+id/BMR"
android:layout_alignStart="#+id/BMR" />
<EditText
android:id="#+id/inage"
android:hint="Please input your age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Sumbit"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/Sumbit"
android:text="Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:text="Your BMR"
android:id="#+id/BMR"
android:textStyle="bold"
android:textSize="10pt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/inheight"
android:layout_alignStart="#+id/inheight" />
<Button
android:text="中文"
android:id="#+id/Toch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/BMR"
android:layout_toLeftOf="#+id/Sumbit"
android:layout_toStartOf="#+id/Sumbit" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_above="#+id/BTbtn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Logcat:
08-24 22:43:52.039 3104-3104/com.example.cmleu_000.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cmleu_000.myapplication, PID: 3104
java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at com.example.cmleu_000.myapplication.MainActivity.onClick(MainActivity.java:92)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
08-24 22:43:53.601 3104-3110/com.example.cmleu_000.myapplication W/art: Suspending all threads took: 8.662ms
08-24 22:44:10.123 3104-3110/com.example.cmleu_000.myapplication W/art: Suspending all threads took: 5.787ms
*new error after edditing
You've defined the maimage variable twice. The class variable maimage that you're trying to access in the onClick(...) method is null (it was never initialized).
To fix this, change:
final ImageView maimage = (ImageView) findViewById(R.id.maimage);
to:
maimage = (ImageView) findViewById(R.id.maimage);
This way you will initialize the class variable instead of defining a new variable with the same name.
The same goes for all the other variables that you're defining again in the onCreate(...) method.

My TextView in Android doesn't update

Although I've checked the solutions for the related questions in this website, I couldn't solve my problem. I'm trying to build a quiz app that takes the correct answer, adds 1 to the score and updates the score on the score TextView. I tried calling the score method through android:onClick and also tried the setOnClickListener methods but none of them seem to work.
This is my XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the Canada Quiz"
android:textSize="16sp"
android:textColor="#000000"
android:textStyle="bold"
android:layout_marginBottom="16dp"
android:layout_gravity="center"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter name"
android:layout_marginBottom="8dp"
/>
<TextView
android:id="#+id/scoreText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginBottom="16dp"
android:textColor="#000000"
android:textStyle="bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1. What is the capital of Canada?"
android:textSize="20dp"
android:textColor="#000000"
android:textStyle="bold"
/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/tokyo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tokyo"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:textSize="16dp"/>
<RadioButton
android:id="#+id/newYork"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New York"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:textSize="16dp"/>
<RadioButton
android:id="#+id/ottawa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ottawa"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:textSize="16dp"/>
<RadioButton
android:id="#+id/hongKong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hong Kong"
android:layout_marginLeft="24dp"
android:textStyle="bold"
android:onClick="calculateScore"
android:textSize="16dp"/>
</RadioGroup>
<Button
android:id="#+id/scoreButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Calculate score"
android:layout_marginTop="16dp"
/>
</LinearLayout>
</ScrollView>
And this is my Java:
public class MainActivity extends AppCompatActivity {
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioButton rb = (RadioButton)findViewById(R.id.ottawa);
Button calculate = (Button) findViewById(R.id.scoreButton);
final TextView scoreShow = (TextView) findViewById(R.id.scoreText);
final boolean rbChecked = rb.isChecked();
calculate.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
if(rbChecked){
score += 1;
scoreShow.setText("Your score is: " + score + "/10");
}
}
});
}
// public void calculateScore(){
// RadioButton rb = (RadioButton)findViewById(R.id.ottawa);
// //Button calculate = (Button) findViewById(R.id.scoreButton);
// TextView scoreShow = (TextView) findViewById(R.id.scoreText);
//
// boolean rbChecked = rb.isChecked();
// if(rbChecked){
// score += 1;
// scoreShow.setText("Your score is: " + score + "/10");
// }
// }
}
Honestly, it really looks like it would work but it doesn't.
You are only storing the value of the checked state when the view is loaded and it never is updated.
Always check rb.isChecked() inside the click listener instead of storing the boolean value outside of it.
It should be:
if(rbChecked.isChecked()){
score += 1;
scoreShow.setText("Your score is: " + score + "/10");
}
you need to check for the state of radiobutton when user click on calculate button....your code should be like this...
calculate.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
rbChecked = rb.isChecked();
if(rbChecked){
score += 1;
scoreShow.setText("Your score is: " + score + "/10");
}
}
});

Dynamic Xml (I think)

EDIT: Thank you all for your help. I edited my Database class to contain the following
final EditText firstName = (EditText) findViewById(R.id.editText1); // First Name
final EditText middleName = (EditText) findViewById(R.id.editText2); // Middle Name
final EditText birthDate = (EditText) findViewById(R.id.editText4); // Birth Date
final String firstname = firstName.getText().toString(); // First Name
final String middlename = middleName.getText().toString(); // Middle Name
final String birthdate = birthDate.getText().toString(); // Birth Date
TextView firstNameText = (TextView)findViewById(R.id.firstname);
TextView middleNameText = (TextView)findViewById(R.id.middlename);
TextView birthDateText = (TextView)findViewById(R.id.birthdate);
firstNameText.setText(firstname);
middleNameText.setText(middlename);
birthDateText.setText(birthdate);
and my database.xml now shows
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:background="#aa0000"
android:gravity="center_horizontal"
android:layout_span="3"
android:id="#+id/firstname"/>
<TextView
android:background="#00aa00"
android:gravity="center_horizontal"
android:layout_span="3"
android:id="#+id/middlename"/>
<TextView
android:background="#0000aa"
android:gravity="center_horizontal"
android:layout_span="3"
android:id="#+id/birthdate"/>
</TableRow>
but when I run the emulator and I try to access that screen (by clicking a button from the previous screen) the application crashes? I set up the button correctly using the OnClickListener so I'm fairly sure the button is not the problem
If you're having trouble understanding the interface here's an example you can cut and paste.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Name: "
android:id="#+id/firstLabel"
android:layout_marginTop="14dip"
android:layout_marginBottom="14dip"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/firstEdit"
android:text="John"
android:layout_toRightOf="#id/firstLabel"
android:layout_alignParentRight="true"></EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Middle Name: "
android:id="#+id/middleLabel"
android:layout_below="#id/firstLabel"
android:layout_marginTop="14dip"
android:layout_marginBottom="14dip"/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/middleEdit"
android:text="Phillip"
android:layout_below="#id/firstEdit"
android:layout_toRightOf="#id/middleLabel"
android:layout_alignParentRight="true"></EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Last Name: "
android:id="#+id/lastLabel"
android:layout_below="#id/middleLabel"
android:layout_marginTop="14dip"
android:layout_marginBottom="14dip"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/lastEdit"
android:text="Doe"
android:layout_below="#id/middleEdit"
android:layout_toRightOf="#id/lastLabel"
android:layout_alignParentRight="true"></EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Birthdate: "
android:id="#+id/birthLabel"
android:layout_below="#id/lastLabel"
android:layout_marginTop="14dip"
android:layout_marginBottom="14dip"
/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/birthEdit"
android:text="08/09/1977"
android:layout_toRightOf="#id/lastLabel"
android:layout_below="#id/lastEdit"
android:layout_alignParentRight="true"></EditText>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_below="#id/birthEdit">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:background="#aa0000"
android:gravity="center_horizontal"
android:layout_span="3"
android:text="something"
android:id="#+id/firstTable"/>
<TextView
android:background="#00aa00"
android:gravity="center_horizontal"
android:layout_span="3"
android:text="something1"
android:id="#+id/middleTable"/>
<TextView
android:background="#0000aa"
android:gravity="center_horizontal"
android:layout_span="3"
android:text="something2"
android:id="#+id/birthTable"/>
</TableRow>
</LinearLayout>
</RelativeLayout>
DatabaseExample.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class DatabaseExample extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Setup edit fields
EditText firstEdit = (EditText)findViewById(R.id.firstEdit);
EditText middleEdit = (EditText)findViewById(R.id.middleEdit);
EditText lastEdit = (EditText)findViewById(R.id.lastEdit);
EditText birthEdit = (EditText)findViewById(R.id.birthEdit);
//Get the text and store in variables
String firstName = firstEdit.getText().toString();
String middleName = middleEdit.getText().toString();
String lastName = lastEdit.getText().toString();
String birthDate = birthEdit.getText().toString();
//setup the text fields
TextView firstTable = (TextView)findViewById(R.id.firstTable);
TextView middleTable = (TextView)findViewById(R.id.middleTable);
TextView birthTable = (TextView)findViewById(R.id.birthTable);
//change the text fields
firstTable.setText(firstName);
middleTable.setText(middleName);
birthTable.setText(birthDate);
}
}
Once again this would be just the interface for inputting and displaying data. Instead of storing the data in String variables you would use SQLite, SharedPreferences, or write to a file on the SDCard.
Try as follows
final EditText firstName = (EditText) findViewById(R.id.editText1);
TextView firstNameTxt = (TextView)findViewById(R.id.firstname);
firstNameTxt.setText(firstName);
You cannot store values from the user in the strings.xml file. You must have a data store such as SharedPreferences or SQLite. Here is another link for help on data storage with Android.

Categories