App crashes after button click - java

I created an Android app which saves the score of two teams. Both teams has buttons to give them 1, 2 or 3 points. And there is a reset button which resets both teams score to 0. It looks like this.
When I click on Reset (both teams has 0 score) nothing happens, but when I click on a button which should add points to a team, the app crashes.
First of all I defined the scores of the teams (in global scope of course).
int teamAScore = 0;
int teamBScore = 0;
Then I wrote methods for adding points to the score. For example adding 3 points for Team A.
private void addTeamA3(View view){
teamAScore += 3;
updateA(teamAScore);
}
The updateA() method refreshes Team A's score.
private void updateA(int score){
TextView ascore = (TextView) findViewById(R.id.textView3);
ascore.setText(score);
}
But exactly here the app crashes. It crashes when I try to add points to a team. But when I reset the points (both scores are 0) nothing happens.
private void reset(View view){
teamAScore = 0;
teamBScore = 0;
updateA(teamAScore);
updateB(teamBScore);
}
The problem could be a NullPointerException, I am not sure but I hope you can help me at this. I am still new to Android programming.
Java code:
package com.example.android.justjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int teamAScore = 0;
int teamBScore = 0;
private void addTeamA3(View view){
teamAScore += 3;
updateA(teamAScore);
}
private void addTeamA2(View view){
teamAScore += 2;
updateA(teamAScore);
}
private void addTeamAFreeThrow(View view){
teamAScore++;
updateA(teamAScore);
}
private void addTeamB3(View view){
teamBScore += 3;
updateB(teamAScore);
}
private void addTeamB2(View view){
teamBScore += 2;
updateB(teamBScore);
}
private void addTeamBFreeThrow(View view){
teamBScore++;
updateB(teamBScore);
}
private void reset(View view){
teamAScore = 0;
teamBScore = 0;
updateA(teamAScore);
updateB(teamBScore);
}
private void updateA(int score){
TextView ascore = (TextView) findViewById(R.id.textView3);
ascore.setText(score);
}
private void updateB(int score){
TextView bscore = (TextView) findViewById(R.id.textView4);
bscore.setText(score);
}
}
XML code:
<?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="com.example.android.justjava.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="59dp"
android:layout_marginTop="16dp"
android:text="Team A"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Team B"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginRight="59dp"
app:layout_constraintRight_toRightOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="60sp"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="#+id/textView"
android:layout_marginLeft="65dp"
app:layout_constraintLeft_toLeftOf="parent" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="60sp"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="#+id/textView2"
android:layout_marginRight="65dp"
app:layout_constraintRight_toRightOf="parent" />
<Button
android:id="#+id/button4"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="+3 POINTS"
android:layout_marginLeft="28dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="#+id/textView3"
android:onClick="addTeamA3"/>
<Button
android:id="#+id/button5"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="+2 POINTS"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="#+id/button4"
android:layout_marginLeft="28dp"
app:layout_constraintLeft_toLeftOf="parent"
android:onClick="addTeamA2"/>
<Button
android:id="#+id/button6"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Free throw"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="#+id/button5"
android:layout_marginLeft="28dp"
app:layout_constraintLeft_toLeftOf="parent"
android:onClick="addTeamAFreeThrow"/>
<Button
android:id="#+id/button7"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="+3 POINTS"
android:layout_marginRight="28dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="#+id/textView4"
android:onClick="addTeamB3"/>
<Button
android:id="#+id/button10"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="+2 POINTS"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="#+id/button7"
android:layout_marginRight="28dp"
app:layout_constraintRight_toRightOf="parent"
android:onClick="addTeamB2"/>
<Button
android:id="#+id/button11"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Free throw"
android:layout_marginRight="28dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="#+id/button10"
android:onClick="addTeamBFreeThrow"/>
<Button
android:id="#+id/button12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="57dp" />

change methods access from private to public
public void addTeamA3(View view){
teamAScore += 3;
updateA(teamAScore);
}
public void addTeamA2(View view){
teamAScore += 2;
updateA(teamAScore);
}
public void addTeamAFreeThrow(View view){
teamAScore++;
updateA(teamAScore);
}
public void addTeamB3(View view){
teamBScore += 3;
updateB(teamBScore);// teamBScore
}
public void addTeamB2(View view){
teamBScore += 2;
updateB(teamBScore);
}
public void addTeamBFreeThrow(View view){
teamBScore++;
updateB(teamBScore);
}
public void reset(View view){
teamAScore = 0;
teamBScore = 0;
updateA(teamAScore);
updateB(teamBScore);
}
as others have mentioned change integer value of score to string
Team A
ascore.setText(Integer.toString(score));
Team B
bscore.setText(Integer.toString(score));
and you forgot to call reset method from xml, add following to reset button
android:onClick="reset"

The Problem is, that ascore.setText(score) passes an integer to the setText method. The setText(int) method looks for a resource with the given id. You need to parse your points to a String. Try ascore.setText(Integer.toString(score)) instead

Related

Doesn't output the result in android studio

I wanted to write a code that converts from rubles to dollars and euros. It seems that everything was written normally, but the translation result does not output. It seems to me that the whole problem comes from the fact that I somehow wrote the wrong **button Text **, or an incorrect condition check. Here is the code:
XML:
<?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=".MainActivity">
<EditText
android:layout_width="120dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:inputType="number"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.275"
android:id="#+id/solution"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/btnEur"
android:layout_width="66dp"
android:layout_height="72dp"
android:gravity="center"
android:text="EUR"
app:cornerRadius="32dp"
android:textSize="15sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.895"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.525">
</com.google.android.material.button.MaterialButton>
<com.google.android.material.button.MaterialButton
android:id="#+id/btnUsd"
android:layout_width="66dp"
android:layout_height="72dp"
android:gravity="center"
android:text="USD"
android:textSize="15sp"
app:cornerRadius="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.139"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.525">
</com.google.android.material.button.MaterialButton>
<TextView
android:layout_width="match_parent"
android:layout_height="140dp"
android:gravity="center"
android:textSize="55sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.996"
android:id="#+id/result"/>
</androidx.constraintlayout.widget.ConstraintLayout>
JAVA:
package com.example.currencyconverter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.material.button.MaterialButton;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView result;
EditText solution;
MaterialButton usd, eur;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = findViewById(R.id.result);
solution = findViewById(R.id.solution);
usd = findViewById(R.id.btnUsd);
eur = findViewById(R.id.btnEur);
}
void assignId(MaterialButton btn, int id) {
btn = findViewById(id);
btn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
MaterialButton button = (MaterialButton) view;
String buttonTxt = button.toString();
if (buttonTxt.equals("USD")) {
String usd = solution.getText().toString();
double usd1 = Double.parseDouble(usd);
usd1 = usd1 / 74.76;
String usd2 = String.valueOf(usd1);
result.setText(usd2 + " DOLLAR");
}
if (buttonTxt.equals("EUR")) {
String eur = solution.getText().toString();
double eur1 = Double.parseDouble(eur);
eur1 = eur1 / 79.61;
String eur2 = String.valueOf(eur1);
result.setText(eur2 + " EURO");
}
}
}
I tried to write return after each if, but it didn't help either
First, i don"t understand the utility of assignId, it's never used.
Secondly i think that would be easier to do that :
TextView result;
EditText solution;
Button usd, eur;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = findViewById(R.id.result);
solution = findViewById(R.id.solution);
usd = findViewById(R.id.btnUsd);
eur = findViewById(R.id.btnEur);
usd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String usd = solution.getText().toString();
double usd1 = Double.parseDouble(usd);
usd1 = usd1 / 74.76;
String usd2 = String.valueOf(usd1);
result.setText(usd2 + " DOLLAR");
}
});
eur.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String eur = solution.getText().toString();
double eur1 = Double.parseDouble(eur);
eur1 = eur1 / 79.61;
String eur2 = String.valueOf(eur1);
result.setText(eur2 + " EURO");
}
});
}
}
use this xml code with my code and that will work :
<?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=".MainActivity">
<EditText
android:layout_width="120dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:inputType="number"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.275"
android:id="#+id/solution"/>
<Button
android:id="#+id/btnEur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="72dp"
android:layout_marginRight="72dp"
android:layout_marginBottom="112dp"
android:text="Button"
app:layout_constraintBottom_toTopOf="#+id/result"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:layout_width="match_parent"
android:layout_height="140dp"
android:gravity="center"
android:textSize="55sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.996"
android:id="#+id/result"/>
<Button
android:id="#+id/btnUsd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="112dp"
android:text="Button"
app:layout_constraintBottom_toTopOf="#+id/result"
app:layout_constraintEnd_toStartOf="#+id/btnEur"
app:layout_constraintHorizontal_bias="0.49"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Calculate using TextChangeHandler in android studio

I'm creating an app for a car parking system using android-studio. I am using TextChangedHandler to show the Total Price of the ticket after the user enters the Hours staying. Price differs according to their Vehicle type
Passing of vehicle type from MainActivity.java to Ticket.java works fine. But when I calculate the price and setText to the Total Price, it doesn't display the price.
MainActivity.java (This passes the type of the vehicle as a string to Ticket.java activity)
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
CardView mCar, mBike, mWheeler, mOther;
TextView mTypeCar, mTypeBike, mTypeWheeler, mTypeOther;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCar = (CardView) findViewById(R.id.car);
mCar.setOnClickListener(this);
mBike = (CardView) findViewById(R.id.bike);
mBike.setOnClickListener(this);
mWheeler = (CardView) findViewById(R.id.wheeler);
mWheeler.setOnClickListener(this);
mOther = (CardView) findViewById(R.id.other);
mOther.setOnClickListener(this);
mTypeCar = (TextView) findViewById(R.id.typeCar);
mTypeBike = (TextView) findViewById(R.id.typeBike);
mTypeWheeler = (TextView) findViewById(R.id.typeWheeler);
mTypeOther = (TextView) findViewById(R.id.typeOther);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.car:
String car = mTypeCar.getText().toString();
Intent i = new Intent(MainActivity.this, Ticket.class);
i.putExtra("type", car);
startActivity(i);
break;
case R.id.other:
String other = mTypeOther.getText().toString();
i = new Intent(MainActivity.this, Ticket.class);
i.putExtra("type", other);
startActivity(i);
break;
case R.id.bike:
String bike = mTypeBike.getText().toString();
i = new Intent(MainActivity.this, Ticket.class);
i.putExtra("type", bike);
startActivity(i);
break;
case R.id.wheeler:
String wheeler = mTypeWheeler.getText().toString();
i = new Intent(MainActivity.this, Ticket.class);
i.putExtra("type", wheeler);
startActivity(i);
break;
default:
throw new IllegalStateException("Unexpected value: " + v.getId());
}
}
}
Ticket.java(Price is calculated using the vehicle type)
public class Ticket extends AppCompatActivity {
TextView mTotPrice;
EditText mHours, mVehicleNo;
Button printTicket;
String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket);
Intent i = getIntent();
type = i.getStringExtra("type");
mTotPrice = (TextView) findViewById(R.id.totalPrice);
mHours = (EditText) findViewById(R.id.hours);
mVehicleNo = (EditText) findViewById(R.id.vehicleNO);
printTicket = (Button) findViewById(R.id.btnPrint);
TextChangeHandler tch = new TextChangeHandler();
mHours.addTextChangedListener(tch);
}
private void calculate() {
String stayingHours = mHours.getText().toString();
try {
// convert hours to int
int hoursInInt = Integer.parseInt(stayingHours);
// store price of each vehicle per hour
int price = 0;
if (type.equals("Car")) {
price = 50;
} else if (type.equals("Other")) {
price = 70;
} else if (type.equals("Bike")) {
price = 20;
} else if (type.equals("Tuk-tuk")) {
price = 20;
}
// calculate total price
int totalPrice = price * hoursInInt;
mTotPrice.setText(totalPrice);
} catch (Exception e) {
e.printStackTrace();
}
}
private class TextChangeHandler implements TextWatcher {
public void afterTextChanged(Editable e){
calculate();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int after){
}
}
}
android_ticket.xml
<?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=".Ticket">
<TextView
android:id="#+id/title2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Enter no. of hours staying"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.123" />
<TextView
android:id="#+id/title3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Enter vehicle number"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.322" />
<TextView
android:id="#+id/title4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Ticket Price(Rs)"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.121"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.632" />
<View
android:id="#+id/divider"
android:layout_width="755dp"
android:layout_height="5dp"
android:background="?android:attr/listDivider"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.525" />
<EditText
android:id="#+id/hours"
android:layout_width="600dp"
android:layout_height="60dp"
android:layout_marginTop="40dp"
android:ems="10"
android:inputType="textPersonName"
android:padding="15dp"
android:hint="Select up to 5 hours"
android:textColor="#color/material_on_background_disabled"
android:textSize="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/title2"
app:layout_constraintVertical_bias="0.01" />
<TextView
android:id="#+id/totalPrice"
android:layout_width="369dp"
android:layout_height="63dp"
android:layout_marginTop="40dp"
android:ems="10"
android:inputType="textPersonName"
android:padding="15dp"
android:textColor="#color/material_on_background_disabled"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.36"
app:layout_constraintStart_toEndOf="#+id/title4"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.62" />
<EditText
android:id="#+id/vehicleNO"
android:layout_width="600dp"
android:layout_height="60dp"
android:layout_marginTop="47dp"
android:ems="10"
android:inputType="textPersonName"
android:padding="15dp"
android:hint="Vehicle number"
android:textColor="#color/material_on_background_disabled"
android:textSize="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/title3"
app:layout_constraintVertical_bias="0.032" />
<Button
android:id="#+id/btnPrint"
android:layout_width="243dp"
android:layout_height="57dp"
android:text="Print Ticket"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.77" />
</androidx.constraintlayout.widget.ConstraintLayout>
You should set sting value on mTotPrice
please use this code
mTotPrice.setText(String.valueOf(totalPrice));
mTotPrice.setText(totalPrice) this wont work cause in setText() we require a String as actual parameter ie. .setText(String) and you gave it as .setText(int)
So just add THIS
mTotPrice.setText(String.valueOf(totalPrice));
instead of
mTotPrice.setText(totalPrice)

The math logic stopped working after i put the XML in a nested layout

I've just started with Android Development. The Order button stopped working after putting the textview and increment, decrements button in the nested layout. When i tried running it without the nested layout, the Order Button worked. But with it, the increment and decrements button is only working.
<?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:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Quantity"
android:textAllCaps="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:onClick="decrement"
android:text="-" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp"
android:text="2"
android:textColor="#android:color/black"
android:textSize="16sp" />
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:onClick="increment"
android:text="+" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Price"
android:textAllCaps="true" />
<TextView
android:id="#+id/price_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="10"
android:textColor="#android:color/black"
android:textSize="16sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:onClick="submitOrder"
android:text="ORDER" />
</LinearLayout>
This is the Java Code
package com.example.android.justjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
int quantity = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
displayPrice(quantity * 10);
}
/**
*This method is called when the add/minus button is called
*/
public void increment(View view) {
quantity = quantity + 1;
display(quantity);
}
public void decrement(View view) {
quantity = quantity - 1;
display(quantity);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number) {
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
}
Init your listener directly in Java:
private TextView quantityView;
private TextView priceView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
this.quantityView = findViewById(R.id.quantity_text_view);
this.priceView = findViewById(R.id.price_text_view);
TextView decrementTextView = findViewById(R.id.decrement_view);
decrementTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
decrement();
}
});
Button incrementView = findViewById(R.id.increment_view);
incrementView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment();
}
});
Button submitOrderView = findViewById(R.id.submit_order_view);
submitOrderView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitOrder();
}
});
}
public void submitOrder() {
displayPrice(quantity * 10);
}
/**
*This method is called when the add/minus button is called
*/
public void increment() {
quantity = quantity + 1;
display(quantity);
}
public void decrement() {
quantity = quantity - 1;
display(quantity);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
quantityView.setText("" + number);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number) {
priceView.setText(NumberFormat.getCurrencyInstance().format(number));
}
<?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:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Quantity"
android:textAllCaps="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/decrement_view"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:text="-" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp"
android:text="2"
android:textColor="#android:color/black"
android:textSize="16sp" />
<Button
android:id="#+id/increment_view"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:text="+" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Price"
android:textAllCaps="true" />
<TextView
android:id="#+id/price_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="10"
android:textColor="#android:color/black"
android:textSize="16sp" />
<Button
android:id="#+id/submit_order_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="ORDER" />
</LinearLayout>

when i hit the "+" button, i was supposed to get 2 to be displayed and hitting it again should get me 3.

this is the part of concern-------
public void incrementQ(View view) {
int variableI = 2;
variableI = variableI + 1;
display(variableI);
}
this question is regarding the Udacity's Basics Android Development Program Lesson no. 1 Making an app interactive: part 1.......18. Quiz:Update quantity variable
this is the complete code of MainActivity.java below-----
package com.example.user1.a1;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
int variableC = 2;
display(variableC);
displayPrice(variableC * 5);
}
public void incrementQ(View view) {
int variableI = 2;
variableI = variableI + 1;
display(variableI);
}
public void decrementQ(View view){
int variableD = 2;
variableD = variableD - 1;
display(variableD);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number) {
TextView priceTextView = (TextView) findViewById(R.id.pricein$);
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
this is the xml code..just in case
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_height="match_parent"
tools:context="com.example.user1.a1.MainActivity"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="#string/quantity"
android:textAllCaps="true" />
<Button
android:id="#+id/button2"
android:layout_width="48dp"
android:layout_height="48dp"
android:onClick="incrementQ"
android:text="#string/goonakar" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/_0"
android:textColor="#000000"
android:textSize="16sp" />
<Button
android:id="#+id/button3"
android:layout_width="48dp"
android:layout_height="48dp"
android:onClick="decrementQ"
android:text="#string/bhagakar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/price"
android:textColor="#000000"
android:textSize="16sp" />
<TextView
android:id="#+id/pricein$"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/$0"
android:textColor="#000000"
android:textSize="16sp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="submitOrder"
android:text="#string/order"
android:textAllCaps="true" />
</LinearLayout>
It seems really weird that you are reinitializing the variableI in every call. You should try to put all variables outside of the function:
int variableI = 2;
public void incrementQ(View view) {
variableI = variableI + 1;
display(variableI);
}
This could possibly be required to be applied in multiple locations in your code.

How can i do a "return back" button in Java?

I have an app that counts the score in a basketball match.
There are three buttons for each team to increase the score (+3, +2, free throw).
I want to create a button to return back in case the user click a button for mistake.
Without creating three separate buttons for each score (+3,+2,+1). But i don't really know how to transform this in Java code.
Something like: Score=score-lastNumberAdded. Sorry for my english.
This is the code:
XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="4dp"
android:text="Team A"
android:textSize="14sp"
android:textColor="#616161"
android:fontFamily="sans-serif-medium"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp" />
<TextView
android:id="#+id/team_a_score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="4dp"
android:text="0"
android:textSize="56sp"
android:textColor="#000000"
android:fontFamily="sans-serif-light"
android:layout_marginBottom="24dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="+3 Points"
android:onClick="addThreeforTeamA" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="+2 Points"
android:onClick="addTwoforTeamA" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="+1 Point"
android:onClick="addOneforTeamA" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray"
android:layout_marginTop="16dp"
android:layout_marginBottom="50dp"/>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="4dp"
android:text="Team B"
android:textSize="14sp"
android:textColor="#616161"
android:fontFamily="sans-serif-medium"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp" />
<TextView
android:id="#+id/team_b_score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="4dp"
android:text="0"
android:textSize="56sp"
android:textColor="#000000"
android:fontFamily="sans-serif-light"
android:layout_marginBottom="24dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="+3 Points"
android:onClick="addThreeforTeamB" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="+2 Points"
android:onClick="addTwoforTeamB" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="+1 Point"
android:onClick="addOneforTeamB" />
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Reset"
android:onClick="reset" />
</RelativeLayout>
JAVA
package com.example.android.courtcounter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int scoreTeamA=0;
int scoreTeamB=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Displays the given score for Team A.
*/
public void displayForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score);
scoreView.setText(String.valueOf(score));
}
/**
* Displays the given score for Team B.
*/
public void displayForTeamB(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_b_score);
scoreView.setText(String.valueOf(score));
}
public void addThreeforTeamA(View v) {
scoreTeamA+=3;
displayForTeamA(scoreTeamA);
}
public void addTwoforTeamA(View v) {
scoreTeamA+=2;
displayForTeamA(scoreTeamA);
}
public void addOneforTeamA(View v) {
scoreTeamA+=1;
displayForTeamA(scoreTeamA);
}
public void addThreeforTeamB(View v) {
scoreTeamB+=3;
displayForTeamB(scoreTeamB); }
public void addTwoforTeamB(View v) {
scoreTeamB+=2;
displayForTeamB(scoreTeamB); }
public void addOneforTeamB(View v) {
scoreTeamB+=1;
displayForTeamB(scoreTeamB); }
public void reset(View v) {
scoreTeamA=0;
scoreTeamB=0;
displayForTeamA(scoreTeamA);
displayForTeamB(scoreTeamB); }
}
Undo problems beg for a Stack to be used since it's a Last In First Out (LIFO) and efficient data structure. That means, in your case, every time a new score is added it will be sitting at the top. The score before that will be sitting just below it and so on and so forth. Therefore, when you start to undo you simply pop() off the top element, subtract it from the score, and re-display the score.
Since a stack is incredibly easy to implement and because you can add couple minor modifications to aid in your program, I see this as one of those times you take it upon yourself to create your own light-weight ScoreStack; like so:
public class ScoreStack {
private class ScoreNode {
int score;
ScoreNode next;
ScoreNode(int score, ScoreNode next) {
this.score = score;
this.next = next;
}
}
private int score = 0;
private ScoreNode root = null;
public void push(int score) {
root = new ScoreNode(score, root);
this.score += score;
}
public int pop() {
if (root == null) {
return 0;
}
int score = root.score;
root = root.next;
this.score -= score;
return score;
}
public void reset() {
root = null;
}
#Override
public String toString() {
return String.valueOf(score);
}
}
With this you're able to keep track of the ever-changing score, provide a simple means for obtaining the current score in String format, and do it all with relative ease and efficiency. Of course, this changes your design slightly so here's an example.
public void addOneforTeamA(View v) {
aTeamStack.push(1);
displayForTeamA();
}
public void undoLastForA() {
aTeamStack.pop();
displayForTeamA();
}
public void displayForTeamA() {
((TextView) findViewById(R.id.team_a_score)).setText(aTeamStack);
}
Unrelated
Additionally, you have a number of improvements you could consider. It could be a sign the design could be better when you're providing the same functionality in methods which only differ by signature. For example, displayForTeamA() and its counterpart for TeamB could be displayScore(int id, String score); like so:
public void displayScore(int id, String score) {
((TextView) findViewById(id)).setText(score);
}
and called like:
displayScore(R.id.team_a_score, aTeamStack);
This is true for all of the team specific methods you have. That is, with a little effort towards design you can achieve a cleaner result.
Set an additional variable for each team, updating its values each time a button is pressed. This version would only be able to undo the very last action. If you want to be able to undo all previous added values, you would have to use a list of all previously added values.
Example for team A:
int lastAddA=0;
public void addThreeforTeamA(View v) {
scoreTeamA+=3;
lastAddA = 3;
displayForTeamA(scoreTeamA);
}
public void undoLastTeamA(View v) {
scoreTeamA-=lastAddA;
lastAddA = 0;//Reset to default
displayForTeamA(scoreTeamA);
}

Categories