Spinner not displaying entries - java

I have two spinners, one where the user selects the food type and a second that is meant to display the food (e.g. Breakfast and Porridge). However my second spinner isn't displaying my foods. Why would this appear? Below is my MainActivity class and my Food class code.
private void chooseBreakfast() {
planspinner1 = (Spinner) findViewById(R.id.planspinner);
List<Food> planlist = new ArrayList<Food>();
planlist.add(new Food("Porridge-35g/140cal",4));
planlist.add(new Food("Coffee-10g/10cal",1));
planlist.add(new Food("Toast-30g/90cal",3));
for(int i =0;i<planlist.size();i++){
System.out.println(planlist.get(i).getName()+ "has" + planlist.get(i).getCalories()+ "calories.");
}
ArrayAdapter<Food> planAdapter1 = new ArrayAdapter<Food>(this,android.R.layout.simple_spinner_item, planlist);
planAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
planspinner1.setAdapter(planAdapter1);
}
public class Food {
private String mstrName;
private int mintCalories;
public Food(String pstrName, int pintCalories) {
mstrName = pstrName;
mintCalories = pintCalories;
}
public String getName() {
return mstrName;
}
public int getCalories() {
return mintCalories;
}
}
Why would my second spinner appear like this?

Override toString() method of your Food class and it might work.
public class Food {
private String mstrName;
private int mintCalories;
public Food(String pstrName, int pintCalories) {
mstrName = pstrName;
mintCalories = pintCalories;
}
public String getName() {
return mstrName;
}
public int getCalories() {
return mintCalories;
}
public String toString() {
return getName();
}
}

Related

How to create an object for generic class?

This is a generic class with bound type Player.
public class Team<T extends Player> implements Comparable<Team<T>> {
private String name;
private int played=0;
private int won=0;
private int lost=0;
private int tide=0;
private ArrayList<T> members = new ArrayList<>();
public Team(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getWon() {
return won;
}
public boolean addPlayer(T player){
if(members.contains(player)){
System.out.println(player.getName() + " is already on this team" );
return false;
}else{
members.add(player);
System.out.println(player.getName()+" picked for team "+this.name);
return true;
}
}
public int numPlayer(){
return this.members.size();
}
}
This is a generic class with bound Type as Team.
public class League<T extends Team>{
public String name;
private ArrayList<T> league = new ArrayList<>();
public League(String name) {
this.name = name;
}
public boolean addTeam(T team){
if(league.contains(team)){
System.out.println("It is already exist");
return false;
}else{
league.add(team);
return true;
}
}
public void showLeagueTable(){
Collections.sort(league);
for(T t:league){
System.out.println(t.getName()+" : "+t.ranking());
}
}
}
I don't know how to create an object for the League class, literally not able to figure out how to mention type. I've tried several ways, but none of them worked for me. Could you guys help me with this code?

How to use polymorphism to access a method inside a subclass that is not defined in the super class using a reference variable of a superclass

If i have 2 classes the first one is BasicHamburger
public class BasicHamburger {
private String breadRollType;
private String meat;
private boolean lettuce;
private boolean tomato;
private boolean carrot;
private boolean cheese;
private int numberOfAdditions;
private int price;
public BasicHamburger(String breadRollType , String meat ,int price){
this.breadRollType = breadRollType;
this.meat = meat;
this.price = price;
lettuce = false;
tomato = false;
carrot = false;
cheese = false;
numberOfAdditions = 0;
}
public void addLettuce(){
lettuce = true;
incrementNumberOfAdditions();
}
public void addTomato(){
tomato = true;
incrementNumberOfAdditions();
}
public void addCarrot(){
carrot = true;
incrementNumberOfAdditions();
}
public void addCheese(){
cheese = true;
incrementNumberOfAdditions();
}
public int getNumberOfAdditions(){
return numberOfAdditions;
}
protected int incrementNumberOfAdditions(){
return ++numberOfAdditions;
}
public boolean isLettuce() {
return lettuce;
}
public boolean isTomato() {
return tomato;
}
public boolean isCarrot() {
return carrot;
}
public boolean isCheese() {
return cheese;
}
public int getBasicHamburgerPrice(){
return price;
}
public int getLettucePrice(){
return 20;
}
public int getTomatoPrice(){
return 15;
}
public int getCheesePrice(){
return 40;
}
public int getCarrotPrice(){
return 10;
}
public int getTotalBasicHamburgerPrice(){
if(isCarrot()){
price = price + 10;
}
if(isCheese()){
price = price + 40;
}
if(isTomato()){
price = price + 15;
}
if(isLettuce()){
price = price + 20;
}
return price;
}
public void displayBurgerDetailsWithPrices(){
if(isCarrot()){
System.out.println("Carrot addition = "+getCarrotPrice());
}
if(isCheese()){
System.out.println("Cheese addition = "+getCheesePrice());
}
if(isTomato()){
System.out.println("Tomato addition = "+getTomatoPrice());
}
if(isLettuce()){
System.out.println("Lettuce addition = "+getLettucePrice());
}
System.out.println("Basic Hamburger Total Price Without Additions = "+getBasicHamburgerPrice());
System.out.println("Basic Hamburger Total Price After Additions= "+getTotalBasicHamburgerPrice());
}
}
the second class is HealthyBurger
public class HealthyBurger extends BasicHamburger{
private boolean onion;
private boolean bacon;
public HealthyBurger(){
super("Brown Rye ","Mutton",30);
onion = false;
bacon = false;
}
public boolean isOnion() {
return onion;
}
public boolean isBacon() {
return bacon;
}
public void addOnion(){
onion = true;
incrementNumberOfAdditions();
}
public void addBacon(){
bacon = true;
incrementNumberOfAdditions();
}
public int getOnionPrice(){
return 15;
}
public int getBaconPrice(){
return 20;
}
#Override
public int getTotalBasicHamburgerPrice() {
int newPrice = super.getTotalBasicHamburgerPrice();
if(isBacon()){
newPrice += 20;
}
if(isOnion()){
newPrice +=15;
}
return newPrice;
}
#Override
public void displayBurgerDetailsWithPrices() {
if(isCarrot()){
System.out.println("Carrot addition = "+getCarrotPrice());
}
if(isCheese()){
System.out.println("Cheese addition = "+getCheesePrice());
}
if(isTomato()){
System.out.println("Tomato addition = "+getTomatoPrice());
}
if(isLettuce()){
System.out.println("Lettuce addition = "+getLettucePrice());
}
if(isOnion()){
System.out.println("Onion addition = "+getOnionPrice());
}
if(isBacon()){
System.out.println("Bacon addition = "+getBaconPrice());
}
System.out.println("Healthy Hamburger Total Price Without Additions = "+getBasicHamburgerPrice());
System.out.println("Healthy Hamburger Total Price After Additions= "+getTotalBasicHamburgerPrice());
}
}
in the main i have written this code
public class Main {
public static void DisplayBurger(BasicHamburger burger){
burger.displayBurgerDetailsWithPrices();
}
public static void main(String[] args) {
BasicHamburger ham1 = new BasicHamburger("x","beef",20);
ham1.addCarrot();
ham1.addCheese();
ham1.addLettuce();
ham1.addTomato();
HealthyBurger ham2 = new HealthyBurger();
ham2.addOnion();
ham2.addBacon();
BasicHamburger test = ham2;
DisplayBurger(test);
}
}
My confusion is the test variable can access displayBurgerDetailsWithPrices() function inside HealthyBurger class and can call the isOnion which is inside that function. Whereas if i decided to write that code inside the main i can not access the isOnion() function.
BasicHamburger newBurger = new HealthyBurger();
newBurger.isOnion();
To make the question clear and right to the point , why accessing a function inside a subclass through a overriden function is possible whereas accessing that function directly is not possible when using a variable of the superclass?
BasicHamburger newBurger = new HealthyBurger();
boolean onion = false;
if(newBurger instanceof HealthyBurger)
onion = ((HealthyBurger).isOnion());
To make the question clear and right to the point, why accessing a function inside a subclass through an overridden function is possible whereas accessing that function directly is not possible when using a variable of the superclass?
It calles Polymophism. The object reference BasicHamburger newBurger refers to the instance of class BasicHamburger or any of its children. It means that by default you have access only to the methods declared in BasicHamburger or any of its parent. If you want to call the children's method, you have to cast this reference to the required type.
I would redesign your code, because in general case if you use casting, then it looks like a design problem (repeat: in general; sometimes it really needed).
public abstract class Burger {
protected final String breadRollType;
protected final String meat;
protected final int basePrice;
protected final Set<Ingredient> ingredients;
protected Burger(String breadRollType, String meat, int basePrice, Set<Ingredient> ingredients) {
this.breadRollType = breadRollType;
this.meat = meat;
this.basePrice = basePrice;
this.ingredients = ingredients == null || ingredients.isEmpty() ? Set.of() : Set.copyOf(ingredients);
}
public final int getBasePrice() {
return basePrice;
}
protected int getIngredientsPrice() {
return ingredients.stream()
.map(Ingredient::getPrice)
.mapToInt(i -> i)
.sum();
}
public int getTotalPrice() {
return basePrice + getIngredientsPrice();
}
public final int getTotalIngredients() {
return ingredients.size();
}
public final boolean hasIngredient(Ingredient ingredient) {
return ingredient != null && ingredients.contains(ingredient);
}
public void printDetailsWithPrices() {
System.out.println(breadRollType + ' ' + meat);
System.out.println("----");
System.out.println("Basic price: " + basePrice);
System.out.println("Ingredients price: " + getIngredientsPrice());
ingredients.forEach(ingredient -> System.out.format("-> %s price: %d\n",
ingredient.getTitle(), ingredient.getPrice()));
System.out.println("Total price: " + getTotalPrice());
}
protected interface Ingredient {
String getTitle();
int getPrice();
}
}
public class HealthyBurger extends Burger {
public HealthyBurger(String breadRollType, String meat, int basePrice, Set<Burger.Ingredient> ingredients) {
super(breadRollType, meat, basePrice, ingredients);
}
public enum Ingredient implements Burger.Ingredient {
ONION("Onion", 15),
BACON("Bacon", 20);
private final String title;
private final int price;
Ingredient(String title, int price) {
this.title = title;
this.price = price;
}
#Override
public String getTitle() {
return title;
}
#Override
public int getPrice() {
return price;
}
}
}
public class PopularBurger extends Burger {
protected PopularBurger(String breadRollType, String meat, int basePrice, Set<Burger.Ingredient> ingredients) {
super(breadRollType, meat, basePrice, ingredients);
}
public enum Ingredient implements Burger.Ingredient {
LETTUCE("Lettuce", 20),
TOMATO("Tomato", 25),
CARROT("Carrot", 10),
CHEESE("Cheese", 40);
private final String title;
private final int price;
Ingredient(String title, int price) {
this.title = title;
this.price = price;
}
#Override
public String getTitle() {
return title;
}
#Override
public int getPrice() {
return price;
}
}
}
public static void main(String... args) {
PopularBurger popularBurger = new PopularBurger("x", "beef", 20,
Set.of(PopularBurger.Ingredient.CARROT,
PopularBurger.Ingredient.CHEESE,
PopularBurger.Ingredient.LETTUCE,
PopularBurger.Ingredient.TOMATO));
HealthyBurger healthyBurger = new HealthyBurger("Brown Rye", "Mutton", 30,
Set.of(HealthyBurger.Ingredient.ONION,
HealthyBurger.Ingredient.BACON));
PopularBurger one = popularBurger;
one.printDetailsWithPrices();
System.out.println();
HealthyBurger two = healthyBurger;
two.printDetailsWithPrices();
System.out.println();
boolean withOnion = two.hasIngredient(HealthyBurger.Ingredient.ONION);
System.out.println(withOnion);
}
x beef
----
Basic price: 20
Ingredients price: 95
-> Cheese price: 40
-> Carrot price: 10
-> Lettuce price: 20
-> Tomato price: 25
Total price: 115
Brown Rye Mutton
----
Basic price: 30
Ingredients price: 35
-> Onion price: 15
-> Bacon price: 20
Total price: 65
true

Java Decorative Pattern Pizza Topping

i have to implement Pizza(American and Neapolitan) decoration pattern with 4 different toppings(Salami,Soudjouk,Onion,Pepper) which extends "TopingDecorator" class and out of them 3 will be added to pizza by "Add Pizza" command.However, the code does not add it to Pizza's TopingDecorator ArrayList. It should be something like below(I am trying to add Salami and Soudjouk to AmericanPan pizza(which extends PlainPizza class)):
AmericanPan a = new American();
Salami s = new Salami(a);
Soudjouk so = new Soudjouk(s);
Here is my PlainPizza class:
public class PlainPizza implements Pizza{
private int cost;
private String name;
private int orderID;
List<ToppingDecorator> topingsOfPizza;
public PlainPizza(int orderID){
this.orderID = orderID;
topingsOfPizza = new ArrayList<ToppingDecorator>();
}
public void addPizza(PlainPizza p) {
Pizza.allPizzas.add(p);
}
public List<ToppingDecorator> getTopingsOfPizza() {
return topingsOfPizza;
}
#Override
public int cost() {
// TODO Auto-generated method stub
return cost;
}
public int getOrderID() {
return orderID;
}
public String getName() {
return name;
}
#Override
public void addTopping() {
}
And here is my AmericanPan class:
public class AmericanPan extends PlainPizza{
// Class Instances
private final int cost = 5;
private String name;
// Constructor
public AmericanPan(int orderID) {
super(orderID);
this.name = "AmericanPan";
}
// Get Cost
#Override
public int cost() {
return cost;
}
// Get Name
public String getName() {
return name;
}
I am tryin to add Salami on American Pan in Salami class:
public class Salami extends ToppingDecorator{
private String name;
ToppingDecorator t;
public Salami(PlainPizza pizza) {
super(pizza);
this.name = "salami";
this.addToping();
}
#Override
public int cost() {
return super.cost() + 3;
}
#Override
public void addTopping() {
t = new Salami(pizza);
pizza.topingsOfPizza.add(t);
}
And I am trying to add it with code below in my function in main class which operates the whole process:
PlainPizza piz = new AmericanPan(orderID);
// Check The Toppings that Pizza contains
if(pizzatops.contains("soudjouk")){
soudjok = true;
}if(pizzatops.contains("salami")){
salami = true;
}if(pizzatops.contains("pepper")){
pepper = true;
}if(pizzatops.contains("onion")){
onion = true;
}
// Add Pizza according to Toppings
for(int g = 0;g<pizzatops.size();g++){
if(pizzatops.get(g).equals("salami")){
Salami s = new Salami(piz);
}else if(pizzatops.get(g).equals("pepper")){
Pepper p = new Pepper(piz);
}else if(pizzatops.get(g).equals("soudjouk")){
Soudjouk p = new Soudjouk(piz);
}
else if(pizzatops.get(g).equals("onion")){
Onion o = new Onion(piz);
}
}
Pizza.allPizzas.add(piz);
System.out.println("AmericanPan pizza added to order " + orderID);
You're going about this all wrong, with the decorator pattern you use different decorator classes to create different type of instances. In your case this means that you can't add multiple toppings to a pizza because the toppings are actually pizzas themselves, so Salami is a salami pizza and Pepper is a pepper pizza and not two toppings
If you want to add multiple toppings to one pizza then Decorator is not the right pattern.
Here is my simplified decorator implementation
interface Pizza {
int cost();
}
public class PlainPizza implements Pizza {
#Override
public int cost() {
return 10;
}
}
public abstract class ToppingDecorator implements Pizza {
private Pizza pizza;
public ToppingDecorator(PlainPizza aPizza) {
pizza = aPizza;
}
#Override
public int cost() {
return pizza.cost();
}
}
public class SalamiPizza extends ToppingDecorator {
public SalamiPizza(PlainPizza aPizza) {
super(aPizza);
}
#Override
public int cost() {
return super.cost() +3;
}
}
public static void main(String[] args) {
SalamiPizza p = new SalamiPizza(new PlainPizza());
System.out.print(p.cost());
}
I tnink, your implementation is wrong. Decorator pattern using interfaces, abstract classes.
Here
You can see, what is the right implementation with Java.

Writing a static method for the following code

I need to write up a static method that takes an array of Vehicles and print each registration number in the array. The object in the array is either a Vehicle, a Car, or a Truck object reference. Finally, I need to print the registration number of the object on a single line on its own.
So the code is:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
public class Car extends Vehicle {
int passengers;
public Car(String rego, int pass) {
super(rego);
passengers = pass;
}
public int getPassengers() {
return passengers;
}
}
public class Truck extends Vehicle {
int tons;
public Truck(String rego, int tons) {
super(rego);
this.tons = tons;
}
public int getTons() {
return tons;
}
}
I have to write up a static method for the following test and get the following, but I am having some trouble.
Test and expected Result
This is what I have done so far:
public static void printRegNum(Vehicle[] list){
for (int i = 0; i < list.length; i++){
System.out.println(list[i]);
}
}
The 1st way to play with your System.out.println(list[i]); is to override the toString() method in class Vehicle:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public String toString() {
return registrationNumber;
}
}
The 2nd way is change:
from:
System.out.println(list[i]);
to:
System.out.println(list[i].getRegistrationNumber());
Hope those can help.
Not getting where's the problem
i.e.
public static void main(String[] args){
Car car = new Car("MYCAR",4);
Truck t = new Truck("MYTRUCK", 16);
Vehicle[] myList = new Vehicle[] {car, t};
printRegNum(myList);
}
Also seems that you only need to print the "rego".
System.out.println(list[i].getRegistrationNumber());

Reorder Recyclerview items with custom adapter

I have a problem that many people had but i don't understand how can i get out of it.
Please help me in my case and do not mark as duplicated.
I have a recyclerview linked with firebase.
My recyclerview has a custom adapter called MyAdapter:
public class MyAdapter extends RecyclerView.Adapter<MyHolder> implements Filterable {
Context c;
ArrayList<Studi> studi;
ArrayList<Studi> filterList;
CustomFilter filter;
public MyAdapter(Context c, ArrayList<Studi> studi) {
this.c = c;
this.studi = studi;
this.filterList = studi;
}
#Override
public MyHolder onCreateViewHolder (ViewGroup parent, int viewType){
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model, parent, false);
MyHolder holder = new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder (MyHolder holder, int position){
String name = studi.get(position).getName();
String desc = studi.get(position).getDescription();
String prof = studi.get(position).getProfessione();
String tel = studi.get(position).getTelefono();
String coord1 = studi.get(position).getCoordinata1();
String coord2 = studi.get(position).getCoordinata2();
String distanza = studi.get(position).getDistanza();
holder.nameTxt.setText(name);
holder.descTxt.setText(desc);
holder.profTxt.setText(prof);
holder.telTxt.setText(tel);
holder.pos1Txt.setText(coord1);
holder.pos2Txt.setText(coord2);
holder.distanza.setText(distanza);
}
#Override
public int getItemCount (){
return (studi == null) ? 0 : studi.size();
}
//FILTER THING......................
public Filter getFilter() {
if(filter == null)
{
filter=new CustomFilter(filterList,this);
}
return filter;
}}
All the items have got a textview inside where it is written the String Distanza. This string is a number for each recyclerview item.
I need to reorder all the recyclerview items from the lower to the higher (Value of the String Distanza).
This is my Studi class which i use for the arraylist:
public class Studi {
private String name;
private String description;
private String professione;
private String telefono;
private String coordinata1;
private String coordinata2;
private String distanza;
public void setDistanza(String distanza) {
this.distanza = distanza;
}
public String getDistanza() {
return distanza;
}
public String getCoordinata2() {
return coordinata2;
}
public void setCoordinata2(String coordinata2) {
this.coordinata2 = coordinata2;
}
public String getCoordinata1() {
return coordinata1;
}
public void setCoordinata1(String coordinata1) {
this.coordinata1 = coordinata1;
}
public String getProfessione() {
return professione;
}
public void setProfessione(String professione) {
this.professione = professione;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public Studi() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}}
So at the end, i need to reorder them at the top of the recyclerview from the ones that return a getDistanza() value lower than the others.
How can i do it? I have really no idea, and sorry but i am new at this.
You can sort your data before passing it to MyAdapter. You can use the sort method from the Collections class. You would have something like this:
Collections.sort(studi, new Comparator<Studi>() {
public int compare(Studi s1, Studi s2) {
return s1.getDistanza() - s2.getDistanza();
}
})
At the end, whenever you filter your data, it always will respect the getDistanza sorting.
You should not sort your data while you are inflating your recyclerView. Infact now that you are already fetching your data from firebase-database, you should use your query accordingly to get the result in sorted form.
If you want your list to be in increasing order of distance (distanza in your case), just use a query something like this
const query = itemsRef.orderByChild('distanza');
This will give you a sorted array which you dont need to sort anymore.
P.S. If you want your recyclerView to have changes in real-time, do not use your custom adapter, instead use the firebaseRecyclerviewAdapter.

Categories