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)
Related
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>
I am using rest API and facing some issue when embedding an API. How do I save spinner and radio button data by value and using retrofit2.This API is for calculating BMR and BMR Please help!
Here is BMIquestions.java
public class BMIquestions extends AppCompatActivity implements View.OnClickListener{
Button nextbtn;
ImageButton date;
DatePickerDialog datePickerDialog;
EditText age, height, weight;
// Let's assume 1 = male and 0 = female
// Declare a RadioGroup object reference
RadioGroup rgGender;
// Declare RadioButton object references for Male and Female
RadioButton rbMale, rbFemale;
private String gender=null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmiquestions);
getSupportActionBar().hide();
nextbtn = findViewById(R.id.Next);
date = findViewById(R.id.calender);
age = findViewById(R.id.age);
height = findViewById(R.id.currentHeight);
weight = findViewById(R.id.currentHeight);
rgGender = findViewById(R.id.gender_group);
rbMale = findViewById(R.id.male);
rbFemale = findViewById(R.id.female);
rgGender.clearCheck();
rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rbMale = group.findViewById(R.id.male);
rbFemale = group.findViewById(R.id.female);
if(rbMale.isSelected()){
rbMale.setTag("1");
rbMale.getTag().toString();
if(rbFemale.isSelected()){
rbFemale.setTag("0");
rbFemale.getTag().toString();
}
}
}
});
findViewById(R.id.female).setOnClickListener(this);
findViewById(R.id.male).setOnClickListener(this);
findViewById(R.id.Next).setOnClickListener(this);
String[] level = new String[]{"Not Very Activ", "Lightly Active", "Active", "Very Active"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this,
R.layout.drop_down_items,
level
);
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.type);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(BMIquestions.this, autoCompleteTextView.getText().toString(), Toast.LENGTH_SHORT).show();
if(autoCompleteTextView.getText().toString().equals("Lightly Active")){
autoCompleteTextView.setTag("1.55");
}
}
});
date.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View view) {
// Calender class 's instance and get current,date ,month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);//current year
int mMonth = c.get(Calendar.MONTH);//current month
int mDay = c.get(Calendar.DAY_OF_MONTH);//current date
final int noofyears = (int) (mYear - c.get(Calendar.YEAR)); //calculate age
//date picker dialog
datePickerDialog = new DatePickerDialog(BMIquestions.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
age.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
DatePicker dp = datePickerDialog.getDatePicker();
WindowManager.LayoutParams params = datePickerDialog.getWindow().getAttributes();
//params.gravity = Gravity.CENTER_HORIZONTAL;
params.width = 50; // dialogWidth;
params.height = 100; // dialogHeight;
datePickerDialog.show();
}
});
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.Next:
openHomePage();
break;
case R.id.male:
gender="0";
break;
case R.id.female:
rbFemale.setTag("0");
gender=rbFemale.getTag().toString();
break;
}
}
public void openHomePage() {
String userHeight = height.getText().toString();
String userWeight = weight.getText().toString();
String userAge = age.getText().toString();
HashMap<String, String> meMap = new HashMap<String, String>();
meMap.put("height", userHeight);
meMap.put("age", userAge);
meMap.put("gender", gender);
//meMap.put("activity_level",act);
meMap.put("current_weight",userWeight);
Call<QuestionResponse> call = RetrofitClient
.getInstance()
.getApi()
.calculation(meMap);
call.enqueue(new Callback<QuestionResponse>() {
#Override
public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
QuestionResponse questionResponse = response.body();
if (response.isSuccessful()) {
if (questionResponse.getStatus().equals("SUCCESS")) {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(BMIquestions.this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<QuestionResponse> call, Throwable t) {
Toast.makeText(BMIquestions.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Intent i=new Intent(BMIquestions.this,HomePage.class);
startActivity(i);
}
}
Here is activity_bmiquestions.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.questions.BMIquestions">
<TextView
android:id="#+id/targetWeight"
android:layout_width="386dp"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto_regular"
android:gravity="center"
android:paddingStart="12dp"
android:paddingTop="60dp"
android:text="Tell us About Youself"
android:textColor="#color/black"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="122dp"
android:fontFamily="#font/roboto_regular"
android:text="Gender:"
android:textColor="#color/black"
android:textSize="14dp" />
<RadioGroup
android:id="#+id/gender_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="142dp"
android:paddingStart="24dp"
android:orientation="horizontal"
>
<RadioButton
android:id="#+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
/>
<RadioButton
android:id="#+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
</RadioGroup>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/age"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="DD/MM/YYYY" />
<ImageButton
android:id="#+id/calender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/ic_baseline_calendar_today_24" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="Height in centimeter"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/currentHeight"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter your height"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="cm"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="When were you born ?"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="Weight in kilogram"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/currentWeight"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter your weight" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kg"
android:textColor="#color/black" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="440dp"
android:layout_marginStart="10dp">
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="330dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="80dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="80dp"
android:hint="Activity Level" >
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/type"
android:inputType="none">
</AutoCompleteTextView>
</com.google.android.material.textfield.TextInputLayout>
</RelativeLayout>
<android.widget.Button
android:id="#+id/Next"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="21dp"
android:background="#color/dark_grey"
android:text="Next"
android:textColor="#color/white"
android:textSize="15sp"
android:textStyle="bold"></android.widget.Button>
</RelativeLayout>
Here is Api Interface
public interface Api{
//GetCalculations
#POST("calculation")
Call<QuestionResponse> calculation(
#Body HashMap<String, String> body
);
}
Here is RetrofitClient.java
package com.example.signup.ui.api;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
//singeleton class defining retrofit client
//define base url
//initialize retrofit object
private static final String BASE_URL = "http://xxx.xxx.xxx.xxx:xxxx/api/";
private static RetrofitClient retrofitClient;
private static Retrofit retrofit;
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
private RetrofitClient() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//return instances when above method call
public static synchronized RetrofitClient getInstance() {
if (retrofitClient==null) {
retrofitClient = new RetrofitClient();
}
return retrofitClient;
}
public Api getApi() {
return retrofit.create(Api.class);
}
}
How can I fix this problem?
I have three fragments in a menu and one of them is the page where I perform the "itu" calculation. When I leave the part corresponding to this uncommented, my app crashes when I click the button.
Below are the codes for my xml and fragment class:
Java class:
public class CalculoFragment extends Fragment {
String temperaturastr;
String umidadestr;
EditText temperatura;
EditText umidade;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_calculo, container, false);
Button botaocalcular = view.findViewById(R.id.botaocalcular);
botaocalcular.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calculo(view);
}
});
return view;
}
public void calculo(View view){
temperatura = (EditText) view.findViewById(R.id.editTextTemp);
umidade = (EditText) view.findViewById(R.id.editTextUmid);
temperaturastr = temperatura.getText().toString();
umidadestr = umidade.getText().toString();
double temperaturavalor = Double.parseDouble(temperaturastr);
double umidadevalor = Double.parseDouble(umidadestr);
double itu=(0.8 * temperaturavalor + (umidadevalor / 100) * (temperaturavalor - 14.4) + 46.4);
if (itu < 72) {
Intent confortotermicoact = new Intent(getActivity(), ConfortoTermicoActivity.class);
startActivity(confortotermicoact);
}
if (itu >= 72 && itu < 80){
Intent brandoact = new Intent(getActivity(), BrandoActivity.class);
startActivity(brandoact);
}
if (itu >= 80 && itu < 90){
Intent moderadoact = new Intent(getActivity(), ModeradoActivity.class);
startActivity(moderadoact);
}
if (itu >= 90 && itu <= 98){
Intent severoact = new Intent(getActivity(), SeveroActivity.class);
startActivity(severoact);
}
XML:
<TextView
android:id="#+id/textView3"
android:layout_width="377dp"
android:layout_height="108dp"
android:text="Para começar, insira os dados abaixo:"
android:textColor="#color/azul"
android:textSize="40sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.47"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.099" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Temperatura do Ar:"
android:textColor="#color/azul"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.077"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.31" />
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/editTextUmid"
android:layout_width="293dp"
android:layout_height="45dp"
android:hint="Umidade Relativa do Ar"
android:inputType="number"
android:textColor="#color/azul"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.135"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.559" />
<Button
android:id="#+id/botaocalcular"
android:layout_width="159dp"
android:layout_height="51dp"
android:background="#color/azul"
android:text="CALCULAR O ESTRESSE TÉRMICO"
android:textSize="15sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.412"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.852">
</Button>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Umidade Relativa do Ar:"
android:textColor="#color/azul"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.102"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.503" />
<EditText
android:id="#+id/editTextTemp"
android:layout_width="309dp"
android:layout_height="49dp"
android:hint="Temperatura do Ar"
android:inputType="number"
android:textColor="#color/azul"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.156"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.365"
/>
Please help me, I've tried everything and I can't get it to work.
The problem is that you are trying to find the view from the fragment layout when you click a button. You have to do that on onCreateView().
The view that you are passing on calculo() is not the fragment.
So, view.findViewById(R.id.editTextTemp) and the other findViewById() that are on calculo() shouldn't be there, put them on onCreateView().
I have a list view of restaurants with 4 different strings: Name, Address, description and tags.
When I click a restaurant it leads me to my detailsActivity.java where I let user edit the name, address, description and tags, and then user can save the edited info to be stored in the list view.
So far when I click save it will only save the data for Name... Address, description and tag strings are not saved with new information.
Here is my code :
public class DetailsActivity extends AppCompatActivity {
private int pos;
//RATE RESTAURANT BUTTON
RatingBar ratingbar1;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Intent i = getIntent();
String name = i.getStringExtra("name");
final String address = i.getStringExtra("address");
String description = i.getStringExtra("description");
String tags = i.getStringExtra("tags");
pos = i.getIntExtra("position", -1); //-1 means not set
EditText ename = findViewById(R.id.editName);
EditText eaddress = findViewById(R.id.editAddress);
EditText edescription = findViewById(R.id.editDescription);
EditText etags = findViewById(R.id.editTags);
ename.setText(name);
eaddress.setText(address);
edescription.setText(description);
etags.setText(tags);
findViewById(R.id.btnSave).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = getIntent();
EditText ename = findViewById(R.id.editName);
EditText eaddress = findViewById(R.id.editAddress);
EditText edescription = findViewById(R.id.editDescription);
EditText etags = findViewById(R.id.editTags);
String name = ename.getText().toString();
String address = eaddress.getText().toString();
String description = edescription.getText().toString();
String tags = etags.getText().toString();
i.putExtra("name", name);
i.putExtra("address", address);
i.putExtra("description", description);
i.putExtra("tags", tags);
i.putExtra("position", pos);
setResult(RESULT_OK, i);
finish();
}
});
Here are my xml files in case they are needed:
activity_details.xml:
<?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=".DetailsActivity"
tools:layout_editor_absoluteY="25dp">
<EditText
android:id="#+id/editName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:ems="10"
android:hint="Restaurant Name"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editAddress"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="Restaurant Address (Street #, City) (***)-***-****"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editName" />
<EditText
android:id="#+id/editDescription"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="Restaurant Description"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editAddress" />
<EditText
android:id="#+id/editTags"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:ems="10"
android:hint="tags"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editDescription" />
<Button
android:id="#+id/btnSave"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Save"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editTags" />
<Button
android:id="#+id/btnMap"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Map"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnSave" />
<Button
android:id="#+id/btnBack"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Back"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnMap" />
<RatingBar
android:id="#+id/rating1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnBack"/>
<Button
android:id="#+id/btnRate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Rate"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rating1" />
Here is activity_main.xml where the listview is located:
<?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">
<Button
android:id="#+id/btnabout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="512dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="about us"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.909"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<EditText
android:id="#+id/editItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:ems="10"
android:hint="New Item"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:text="Add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/editItem" />
<ListView
android:id="#+id/itemList"
android:layout_width="match_parent"
android:layout_height="433dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toTopOf="#+id/editItem"
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="1.0" >
</ListView>
</android.support.constraint.ConstraintLayout>
and finally mainactivity.java which includes my onActivityResult function:
public class MainActivity extends AppCompatActivity {
private ArrayList<Item> items;
private ItemsAdapter itemsAdapter;
private ListView lvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvItems = findViewById(R.id.itemList);
items = new ArrayList<>();
items.add(new Item ("Mcdonalds", "108 queen st", "come get a junior chicken", "fast food"));
items.add(new Item("Pizza Pizza", "9 moms st", "wonderful pizza made by mom", "pizza"));
itemsAdapter = new ItemsAdapter(this, R.layout.row_layout, items);
lvItems.setAdapter(itemsAdapter);
Button btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//ADD NEW ITEM TO LIST
EditText et = findViewById(R.id.editItem);
String text = et.getText().toString();
if(!text.isEmpty())
{
itemsAdapter.add(new Item(text, "default address", "default desc", "default tag"));
et.setText("");
}
}
});
//ABOUT PAGE REDIRECT
Button btn1 = findViewById(R.id.btnabout);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,aboutmembers.class);
startActivity(i);
}
});
//INTERACTION WITH LIST ITEMS (LONG CLICK TO DELETE)
lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final int pos = position;
new AlertDialog.Builder(view.getContext()).setTitle("Warning!")
.setMessage("Do you want to remove this item?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
items.remove(pos);
itemsAdapter.notifyDataSetChanged();
}
}).show();
return true;
}
});
//ADD NEW LISTENER TO LIST
lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(view.getContext(), DetailsActivity.class);
i.putExtra("position", position);
i.putExtra("name", items.get(position).getName());
i.putExtra("address", items.get(position).getAddress());
i.putExtra("description", items.get(position).getDescription());
i.putExtra("tags", items.get(position).getTags());
startActivityForResult(i, EDIT_ITEM);
}
});
}
//DEFINE OUR CALL OF EDIT ITEM
public static final int EDIT_ITEM = 1;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==EDIT_ITEM)
{
if(resultCode==RESULT_OK)
{
int pos = data.getIntExtra("position", -1);
if(pos!=-1)
{
String name = data.getStringExtra("name");
String address = data.getStringExtra("address");
String description = data.getStringExtra("description");
String tags = data.getStringExtra("tags");
Item item = items.get(pos);
item.setName(name);
items.set(pos, item);
itemsAdapter.notifyDataSetChanged();
}
}
}
}
in mainactivity.java in the onActivityResult function set the address/description/tags:
item.setAddress((address));
item.setDescription(description);
item.setTags(tags);
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