Doesn't output the result in android studio - java

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>

Related

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)

Function not called when clicking on a button in Android

I am building a BMR calculator with radio buttons for Male and Female.
I am using a switch case to calculate BMR for each but it doesn't seem to work.
Nothing happens when I press the calculate button.
It seems to work okay when I calculate it directly i.e without switch case, the ResultTextView becomes visible and shows the answers. I apologize if I am repeating the question, I am new to programming. Please ignore the formulae for BMR I know they aren't correct I just put them for testing.
Following is my code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class BmrActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton bmrFemaleRadioButton;
RadioButton bmrMaleRadioButton;
EditText bmrAgeEditText;
EditText bmrWeightEditText;
EditText bmrHeightEditText;
Button bmrCalculateButton;
TextView bmrResultTextView;
Double age;
Double weight;
Double height;
Double resultBmr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmr);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
bmrFemaleRadioButton = findViewById(R.id.bmrFemaleRadioButton);
bmrMaleRadioButton = findViewById(R.id.bmrMaleRadioButton);
bmrAgeEditText = findViewById(R.id.bmrAgeEditText);
bmrWeightEditText = findViewById(R.id.bmrWeightEditText);
bmrHeightEditText = findViewById(R.id.bmrHeightEditText);
bmrCalculateButton = findViewById(R.id.bmrCalculateButton);
bmrResultTextView = findViewById(R.id.bmrResultTextView);
bmrFemaleRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bmrAgeEditText.setVisibility(View.VISIBLE);
bmrWeightEditText.setVisibility(View.VISIBLE);
bmrHeightEditText.setVisibility(View.VISIBLE);
bmrCalculateButton.setVisibility(View.VISIBLE);
}
});
bmrMaleRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bmrAgeEditText.setVisibility(View.VISIBLE);
bmrWeightEditText.setVisibility(View.VISIBLE);
bmrHeightEditText.setVisibility(View.VISIBLE);
bmrCalculateButton.setVisibility(View.VISIBLE);
}
});
}
public void calculateBmr(final View view){
age = Double.parseDouble(bmrAgeEditText.getText().toString());
weight = Double.parseDouble(bmrWeightEditText.getText().toString());
height = Double.parseDouble(bmrHeightEditText.getText().toString());
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.bmrFemaleRadioButton:
resultBmr = age + weight + height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
case R.id.bmrMaleRadioButton:
resultBmr = age * weight * height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
}
}
});
}
}
Following is my XML layout file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BmrActivity">
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="#+id/bmrFemaleRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:text="Female" />
<RadioButton
android:id="#+id/bmrMaleRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:text="Male" />
</RadioGroup>
<EditText
android:id="#+id/bmrAgeEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Enter your age"
android:inputType="number"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/radioGroup" />
<EditText
android:id="#+id/bmrWeightEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:hint="Enter your weight in kgs"
android:inputType="number"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrAgeEditText" />
<EditText
android:id="#+id/bmrHeightEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:hint="Enter your height in cms"
android:inputType="number"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrWeightEditText" />
<Button
android:id="#+id/bmrCalculateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:onClick="calculateBmr"
android:text="Calculate"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrHeightEditText" />
<TextView
android:id="#+id/bmrResultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="monospace"
android:text="Answer"
android:textAlignment="center"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/bmrCalculateButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
You are doing it wrong. You are calling setOnCheckedChangeListener() when the button has been clicked, but by that time the radio button has already been checked. The onCheckedChange() is called when the change occurs.
Instead of setting a listener, you can directly get the checked item id by calling radioGroup.getCheckedRadioButtonId()
like this
switch(radioGroup.getCheckedRadioButtonId()){
case R.id.bmrFemaleRadioButton:
resultBmr = age + weight + height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
case R.id.bmrMaleRadioButton:
resultBmr = age * weight * height;
bmrResultTextView.setText("Your BMR is "+resultBmr);
bmrResultTextView.setVisibility(View.VISIBLE);
break;
}
Did you try move get age, weight, height inside onCheckChanged. Because it only parse one time and not update again.

Saving edit to listview android studio

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);

My app does not load an activity on the device

My android app links to a new activity to allow a user to create their profile and save the strings they use to a firebase database. However, the activity loads but is blank as shown below. This issue only seemed to arise after I added functionality to save user data to firebase.
blank activity
package com.example.eventfeed;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class CreateProfileActivity extends AppCompatActivity {
public static final String INTEREST_KEY = "interest";
public static final String NAME_KEY = "name";
private DocumentReference mDocRef = RegisterActivity.getmDocRef();
private Button createBtn;
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
this.setContentView(R.layout.create_profile_layout);
// Toast.makeText(this, "Create Activity", Toast.LENGTH_SHORT).show();
EditText interestsView = (EditText) findViewById(R.id.interests);
EditText nameView = (EditText) findViewById(R.id.profile_name);
String interests = interestsView.getText().toString();
String name= nameView.getText().toString();
Map<String, Object> dataToSave = new HashMap<>();
mDocRef = FirebaseFirestore.getInstance().document("users/" + ActivityLoginEmail.getEmailStr() + "/profileInfo");
dataToSave.put(INTEREST_KEY, interests);
dataToSave.put(NAME_KEY, name);
mDocRef.set(dataToSave);
createBtn = (Button) findViewById(R.id.createProfileBtn);
createBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CreateProfileActivity.this, Profile.class);
startActivity(intent);
}
});
}
}
The xml files that format the page
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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"
android:id="#+id/create_profile_layout"
tools:context=".CreateProfileActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="?android:attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/main_page_toolbar"
layout="#layout/app_bar_layout">
</include>
<include layout="#layout/create_profile_content"></include>
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/drawer_view">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Create profile activity 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".CreateProfileActivity"
android:id="#+id/create_profile_content"
tools:showIn="#layout/create_profile_layout">
<ImageView
android:id="#+id/imageView"
android:layout_width="0dp"
android:layout_height="200dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/vibe_concert" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginTop="56dp"
android:adjustViewBounds="false"
android:cropToPadding="false"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_goneMarginTop="100dp"
app:srcCompat="#drawable/vibe_image" />
<EditText
android:id="#+id/profile_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="158dp"
android:layout_marginLeft="158dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="156dp"
android:layout_marginRight="156dp"
android:layout_marginBottom="228dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView2"
app:layout_constraintVertical_bias="0.553"
/>
<TextView
android:id="#+id/interest_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="224dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/profile_interest"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.025"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView2"
tools:text="Interests" />
<EditText
android:id="#+id/interests"
android:layout_width="200dp"
android:layout_height="87dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="140dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView4"
app:layout_constraintVertical_bias="0.091" />
<TextView
android:id="#+id/profile_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.679"
app:layout_constraintStart_toEndOf="#+id/textView2"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.544" />
<Button
android:id="#+id/createProfileBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.835"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/interests"
app:layout_constraintVertical_bias="0.473"
tools:text="Create Profile" />
</android.support.constraint.ConstraintLayout>
The method that is called to send the user to the create profile activity
private void LoginUser(){
setEmailStr(email.getText().toString().trim());
String Password = password.getText().toString().trim();
mAuth.signInWithEmailAndPassword(emailStr, Password)
.addOnCompleteListener(this, new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
currentUser = mAuth.getCurrentUser();
finish();
Toast.makeText(ActivityLoginEmail.this, "Create
Activity", Toast.LENGTH_SHORT).show();
setCurrent_user_db(false);
startActivity(new Intent(ActivityLoginEmail.this,
CreateProfileActivity.class));
}else {
setCurrent_user_db(true);
Toast.makeText(ActivityLoginEmail.this, "couldn't login",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
EDIT:After changing the xml file to a simple one with just a single button and adding a toast command to print if the activity loads nothing happens. Therefore the problem is most likely not within the xml files.
EDIT2:I found the solution by removing the PersistableBundle parameter from my oncreate method. Not exactly sure what this does to begin with if anyone would like to elaborate.
public class CreateProfileActivity extends AppCompatActivity {
public static final String INTEREST_KEY = "interest";
public static final String NAME_KEY = "name";
private DocumentReference mDocRef = RegisterActivity.getmDocRef();
private Button createBtn;
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.create_profile_layout);
Toast.makeText(this, "Create Activity", Toast.LENGTH_SHORT).show();
EditText interestsView = (EditText) findViewById(R.id.interests);
EditText nameView = (EditText) findViewById(R.id.profile_name);
String interests = interestsView.getText().toString();
String name= nameView.getText().toString();
Map<String, Object> dataToSave = new HashMap<>();
mDocRef = FirebaseFirestore.getInstance().document("users/" +
ActivityLoginEmail.getEmailStr() + "/profileInfo");
dataToSave.put(INTEREST_KEY, interests);
dataToSave.put(NAME_KEY, name);
mDocRef.set(dataToSave);
createBtn = (Button) findViewById(R.id.createProfileBtn);
createBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CreateProfileActivity.this, Profile.class);
startActivity(intent);
}
});
}
}
try by moveing finish() to the bottom of this condition
if (task.isSuccessful()){
currentUser = mAuth.getCurrentUser();
Toast.makeText(ActivityLoginEmail.this, "Create
Activity", Toast.LENGTH_SHORT).show();
setCurrent_user_db(false);
startActivity(new Intent(ActivityLoginEmail.this,
CreateProfileActivity.class));
finish();
}

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>

Categories