Adding information into an array with super classes - java

The problem I'm having is with the superclass. I can't change the new Property(...) to another class called House. The only difference is the information in them, but once I change it I am getting an error stating that the constructor doesn't match but I thought that the super() should pass the information on.
This is how my Array is set up:
public static void main(String[] args) {
Property [] Properties = new Property[25];
Properties[0] = new Property (1001, 200, "58 Lackagh Park", "Dungiven", "BT47 4ND", new MyDate(15,05,2018), 5000.00, 800.50, 40.50);
Properties[1] = new Property (1002, 500, "24 Jop Lane", "Kelflar", "VT57 5LP", new MyDate(10,06,2018), 12000.00, 1000.00, 60.00);
Properties[2] = new Property (1003, 100, "Lot B", "Bandlebop", "LU49 3JU", new MyDate(01,07,2018), 450.00, 800.00, 50.50);
Properties[3] = new Property (1004, 200, "12 Back Lane", "Galafray", "GA1 1Fy", new MyDate(05,12,2018), 50000.00, 1000.00, 80.00);
Properties[4] = new Property (1005, 200, "43 Pop Street", "Jundar", "BY78 1JH", new MyDate(11,12,2018), 2500.00, 600.50, 32.90);
Properties[5] = new Property (1006, 200, "123 Fake Street", "Dunlem", "BL09 4PL", new MyDate(21,03,2018), 65000.00, 700.50, 56.50);
Properties[6] = new Property (1007, 200, "09012 Bakers Field", "Bristol", "LO87 D0N", new MyDate(15,05,2018), 5000.00, 200.50, 40.50);
Properties[7] = new Property (1008, 200, "Unit B high Street", "LA", "LA58 7NL", new MyDate(18,11,2018), 20000.00, 1000.00, 90.00);
Properties[8] = new Property (1009, 200, "1 Flabbergast Park", "Nubb", "HJ98 7NH", new MyDate(10,03,2018), 4958.00, 900.20, 20.50);
Properties[9] = new Property (1010, 200, "29 Bakers Field", "London Town", "HU84 2JO", new MyDate(02,05,2018), 1234.00, 800.00, 40.50);
Properties[10] = new Property (1011, 200, "20 Peliper Lane", "Dungiven", "BT47 4FE", new MyDate(15,05,2018), 4321.00, 900.00, 20.00);
Here is the Property class:
public class Property {
private int PropertyNumber, SquareFoot;
private String Address,Town,PostCode;
private MyDate DateListed;
public double Price;
private double Rates;
private double PricePerSquareFoot;
public Property() {
PropertyNumber = 0;
SquareFoot = 0;
Address = "";
Town = "";
PostCode = "";
DateListed = new MyDate();
Price = 0.0;
Rates = 0.0;
PricePerSquareFoot = 0.0;
}
public Property(int PropertyNumber, int SquareFoot, String Address, String Town, String PostCode, MyDate DateListed, double Price, double rates, double PricePerSquareFoot)
{
super();
this.PropertyNumber = PropertyNumber;
this.SquareFoot = SquareFoot;
this.Address = Address;
this.Town = Town;
this.PostCode = PostCode;
this.DateListed = DateListed;
this.Price = Price;
this.Rates = Rates;
this.PricePerSquareFoot = PricePerSquareFoot;
}
//--------Getters and setters----------------//
public void setPropertyNumber(int PropertyNumber)
{
this.PropertyNumber = PropertyNumber;
}
public int getPropertyNumber()
{
return PropertyNumber;
}
public void setSquareFoot(int SquareFoot)
{
this.SquareFoot = SquareFoot;
}
public int getSquareFoot()
{
return SquareFoot;
}
public void setAddress(String Address)
{
this.Address = Address;
}
public String getAddress()
{
return Address;
}
public void setTown( String Town)
{
this.Town = Town;
}
public String getTown()
{
return Town;
}
public void setPostcode( String PostCode)
{
this.PostCode = PostCode;
}
public String GetPostcode()
{
return PostCode;
}
public void setDateListed(MyDate DateListed)
{
this.DateListed = DateListed;
}
public MyDate getDateListed()
{
return DateListed;
}
public void setPrice(double Price)
{
this.Price = Price;
}
public double getPrice()
{
return Price;
}
public void setRates(double Rates)
{
this.Rates = Rates;
}
public double getRates()
{
return Rates;
}
public void setPricePerSquareFoot(double PricePerSqaureFoot)
{
this.PricePerSquareFoot = PricePerSquareFoot;
}
public double getPricePerSquareFoot()
{
return PricePerSquareFoot;
}
And this is what I am trying to put into the array along with the property information such as Property number price etc:
public class House extends Residential {
private int Garden;
private int Garage;
public House() {
super();
Garage = 0;
Garden = 0;
}
public House(int Garage, int garden) {
super();
this.Garage = 0;
this.Garden = 0;
}
public void setGarage(int Garage)
{
this.Garage = Garage;
}
public int getGarage()
{
return Garage;
}
public void setGarden(int Garden)
{
this.Garden = Garden;
}
public int getGarden()
{
return Garden;
}
.......
This is the residential class
public class Residential extends Property
{
private int NumberOfBedrooms;
private int NumberOfBathrooms;
public Residential()
{
super();
NumberOfBedrooms = 0;
NumberOfBathrooms = 0;
}
public void setNumberOfBedrooms(int NumberOfBedrooms)
{
this.NumberOfBedrooms = NumberOfBedrooms;
}
public int getNumberOfBedrooms()
{
return NumberOfBedrooms;
}
public void setNumberOfBathrooms(int NumberOfBathrooms)
{
this.NumberOfBathrooms = NumberOfBathrooms;
}
public int getNumberOfBathrooms()
{
return NumberOfBathrooms;
}
public Residential(int NumberOfBedrooms, int NumberOfBathrooms)
{
super();
NumberOfBedrooms = 0;
NumberOfBathrooms = 0;
}

Related

no suitable constructor found(Java)

Trying to create object using aggregation but error shows no suitable constructor when using array to create objects. What I'm trying to understand is why wont the array identify the information implemented as I when I don't provide information on the object it is able to create an object with it's default information from both class' no-arg constructor
public class ComputerTest {
public static void main(String[] args){
Computer c[] = new Computer[5];
c[0] = new Computer("OEM", "Basic");
c[1] = new Computer("Dell", "Optiplex", "discrete", "PCIEx16", 375, "8-pin",16);
c[2] = new Computer("Lenova","IdeaCentre", "integrated", "N/A", 120, "N/A", 4);
c[3] = new Computer("HP", "Omen Obelisk", "discrete", "PCIEx8", 150,"6-pin", 8);
c[4] = new Computer("Lenovo" , "IdeaCentre", "integrated", "N/A", -110, "N/A", 2);
printComputers(c);
}
static void printComputers(Computer c[]){
for (int i=0; i<c.length; i++){
System.out.println(c[i].getInfo());
}
}
Using information from this class
public class Computer {
private String brand;
private String model;
private VideoCard VideoCard;
public Computer(){
this.setBrand("OEM");
this.setModel("Basic");
this.VideoCard = new VideoCard();
}
public Computer(String brand, String model, VideoCard VideoCard){
this.setBrand(brand);
this.setModel(model);
this.setVideoCard(VideoCard);
}
public void setBrand(String brand){
this.brand = brand;
}
public void setModel(String model){
this.model = model;
}
public void setVideoCard(VideoCard VideoCard){
this.VideoCard = VideoCard;
}
public String getBrand(){
return brand;
}
public String getModel(){
return model;
}
public VideoCard getVideoCard(){
return this.VideoCard;
}
public String getInfo(){
String info = String.format("%s " + "%s\n" + "Video Card Info:\n" + "%s\n", getBrand(), getModel(), VideoCard.getInfo());
return info;
}
which aggregates from this class
public class VideoCard {
private String type;
private String connection;
private int power;
private String extPower;
private int memory;
public VideoCard(){
this.setType("integrated");
this.setConnection("N/A");
this.setPower(100);
this.setExtPower("N/A");
this.setMemory(1);
}
public VideoCard(String type, String connection, int power, String extPower, int memory){
this.setType(type);
this.setConnection(connection);
this.setPower(power);
this.setExtPower(extPower);
this.setMemory(memory);
}
public void setType(String type){
this.type = type;
}
public void setConnection(String connection){
this.connection = connection;
}
public void setPower(int power){
if(power>= 1 && power<=300){
this.power = power;
} if(power<1) {
this.power = 75;
} if(power>300){
this.power = 200;
}
}
public void setExtPower(String extPower){
this.extPower = extPower;
}
public void setMemory(int memory){
if(memory>=1 && memory<=12){
this.memory = memory;
} if(memory<1){
this.memory = 1;
} if(memory>12){
this.memory = 12;
}
}
public String getType(){
setType(this.type);
return type;
}
public String getConnection(){
setConnection(this.connection);
return connection;
}
public int getPower(){
setPower(this.power);
return power;
}
public String getExtPower(){
setExtPower(this.extPower);
return extPower;
}
public int getMemory(){
setMemory(this.memory);
return memory;
}
public String getInfo(){
String info = String.format("Type:\t\t%s\n " + "Connection:\t%s\n " + "Power:\t\t%sW \n " + "Ext Power:\t%s\n " + "Memory:\t%dGB \n ",
getType(), getConnection(), getPower(), getExtPower(), getMemory());
return info;
}

DynamicJasper - How to add a subreport as columns?

Overview
I have a Java class which has an ArrayList that must be printed to
the jasperReport as a subreport.
I'm using DynamicJasper library.
The example on this question has been modified so it can be reproduced. However the data is different on the real case.
Problem
The current code Ive come with, prints the subreport in another line. Its ugly. I wanted the subreport to just be a group of columns that are concatenated.
To make it clear, here's the current result
And What I want is something like this:
Current code
public class Test_subReport {
protected static JasperPrint jp;
protected static JasperReport jr;
protected static Map params = new HashMap();
protected static DynamicReport dr;
public static void main(String args[]) throws SQLException, ColumnBuilderException, ClassNotFoundException {
Test_subReport t = new Test_subReport();
t.createReport();
}
public void createReport() throws SQLException, ColumnBuilderException, ClassNotFoundException {
ArrayList<Fruit> createMockDataset = createMockDataset();
Style titleStyle = new Style();
titleStyle.setHorizontalAlign(HorizontalAlign.CENTER);
titleStyle.setFont(Font.ARIAL_SMALL_BOLD);
Style dataStyle = new Style();
dataStyle.setHorizontalAlign(HorizontalAlign.CENTER);
dataStyle.setFont(Font.ARIAL_SMALL);
dataStyle.setBlankWhenNull(true);
final List items = SortUtils.sortCollection(createMockDataset, Arrays.asList(new String[]{"name", "description"}));
FastReportBuilder drb = new FastReportBuilder();
drb.setTemplateFile("templatePortrait.jrxml", true, true, true, true);
drb.addColumn("name", "name", String.class.getName(), 30, dataStyle)
.addColumn("description", "description", String.class.getName(), 50, dataStyle)
.setTitle("Report")
.setSubtitle("")
.setPrintBackgroundOnOddRows(true)
.setUseFullPageWidth(true);
drb.addGroups(2);
try {
drb.addField("evaluations", List.class.getName());
drb.addSubreportInGroupHeader(1, createSubreport("Evaluations"));
} catch (Exception ex) {
Logger.getLogger(Test_subReport.class.getName()).log(Level.SEVERE, null, ex);
}
DynamicReport dynamicReport = drb.build();
dynamicReport.setTitleStyle(titleStyle);
HashMap parametros = new HashMap();
parametros.put("dataRelatorio", MyTools.getDataPorExtenso());
doReport(dynamicReport, items, parametros);
}
public void doReport(final DynamicReport _report, final Collection _data, HashMap parametros) {
try {
JRDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(_data);
JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(_report, new ClassicLayoutManager(), beanCollectionDataSource, parametros);
JasperViewer.viewReport(jasperPrint);
} catch (JRException ex) {
ex.printStackTrace();
}
}
private DynamicReport createHeaderSubreport(String title) throws Exception {
FastReportBuilder rb = new FastReportBuilder();
DynamicReport dr = rb
.addColumn("id", "id", Integer.class.getName(), 100)
.addColumn("score", "score", Double.class.getName(), 50)
.setMargins(5, 5, 20, 20)
.setUseFullPageWidth(true)
.setWhenNoDataNoPages()
.setTitle(title)
.build();
return dr;
}
private Subreport createSubreport(String title) throws Exception {
SubReportBuilder srb = new SubReportBuilder();
srb.setDynamicReport(createHeaderSubreport(title), new ClassicLayoutManager())
.setStartInNewPage(true)
.setDataSource(DJConstants.DATA_SOURCE_ORIGIN_FIELD, DJConstants.DATA_SOURCE_TYPE_COLLECTION, "evaluations");
return srb.build();
}
public ArrayList<Fruit> createMockDataset() {
ArrayList<Fruit> fruits = new ArrayList<>();
Fruit f1 = new Fruit();
f1.name = "Apple X1";
f1.description = "Yummy yummy apple for the stackoverflow readers 1";
Fruit f2 = new Fruit();
f2.name = "Apple Ag";
f2.description = "Yummy yummy apple for the stackoverflow readers 2";
Fruit f3 = new Fruit();
f3.name = "Apple Mn";
f3.description = "Yummy yummy apple for the stackoverflow readers 3";
Fruit f4 = new Fruit();
f4.name = "Apple O2";
f4.description = "Yummy yummy apple for the stackoverflow readers 4";
//Evaluations for f1
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f1.evaluations.add(e);
}
//evaluations for f4
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f4.evaluations.add(e);
}
fruits.add(f1);
fruits.add(f2);
fruits.add(f3);
fruits.add(f4);
return fruits;
}
public class Fruit {
public String name;
public String description;
public ArrayList<Evaluation> evaluations = new ArrayList<Evaluation>();
public Fruit() {
}
public Fruit(String name, String description) {
this.name = name;
this.description = description;
}
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;
}
public ArrayList<Evaluation> getEvaluations() {
return evaluations;
}
public void setEvaluations(ArrayList<Evaluation> evaluations) {
this.evaluations = evaluations;
}
}
public class Evaluation {
public int id;
public double score;
public Evaluation() {
}
public Evaluation(int id, double score) {
this.id = id;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
}
Probably there isn't way to implement desired behavior using subreports.
I guess, that the best way to do it is to use just groups, but data model should be a bit modified for that.
Here is my solution:
public class Test_subReport {
protected static JasperPrint jp;
protected static JasperReport jr;
protected static Map params = new HashMap();
protected static DynamicReport dr;
public static void main(String args[]) throws SQLException, ColumnBuilderException, ClassNotFoundException {
Test_subReport t = new Test_subReport();
t.createReport();
}
public void createReport() throws SQLException, ColumnBuilderException, ClassNotFoundException {
List<DataWrapper> createMockDataset = wrapData(createMockDataset());
Style titleStyle = new Style();
titleStyle.setHorizontalAlign(HorizontalAlign.CENTER);
titleStyle.setFont(Font.ARIAL_SMALL_BOLD);
Style dataStyle = new Style();
dataStyle.setHorizontalAlign(HorizontalAlign.CENTER);
dataStyle.setFont(Font.ARIAL_SMALL);
dataStyle.setBlankWhenNull(true);
final List items = SortUtils.sortCollection(createMockDataset, Arrays.asList(new String[]{"name", "description"}));
FastReportBuilder drb = new FastReportBuilder();
drb.setTemplateFile("templatePortrait.jrxml", true, true, true, true);
drb.addColumn("name", "name", String.class.getName(), 30, dataStyle)
.addColumn("description", "description", String.class.getName(), 100, dataStyle)
.addColumn("id", "id", Integer.class.getName(), 30, dataStyle)
.addColumn("score", "score", Double.class.getName(), 30, false, "$ #.00", dataStyle)
.setTitle("Report")
.setWhenNoDataNoPages()
.setAllowDetailSplit(false)
.setUseFullPageWidth(true);
drb.addGroups(2);
DynamicReport dynamicReport = drb.build();
dynamicReport.setTitleStyle(titleStyle);
HashMap parametros = new HashMap();
parametros.put("dataRelatorio", MyTools.getDataPorExtenso());
doReport(dynamicReport, items, parametros);
}
public void doReport(final DynamicReport _report, final Collection _data, HashMap parametros) {
try {
JRDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(_data);
JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(_report, new ClassicLayoutManager(), beanCollectionDataSource, parametros);
JasperViewer.viewReport(jasperPrint);
} catch (JRException ex) {
ex.printStackTrace();
}
}
public List<DataWrapper> wrapData(List<Fruit> fruits) {
List<DataWrapper> dataList = new ArrayList<>();
for (Fruit fruit : fruits) {
if (fruit.getEvaluations().isEmpty()) {
dataList.add(new DataWrapper(fruit.name, fruit.description, null, null));
} else {
for (Evaluation evaluation : fruit.getEvaluations()) {
dataList.add(new DataWrapper(fruit.name, fruit.description, evaluation.id, evaluation.score));
}
}
}
return dataList;
}
public List<Fruit> createMockDataset() {
ArrayList<Fruit> fruits = new ArrayList<>();
Fruit f1 = new Fruit();
f1.name = "Apple X1";
f1.description = "Yummy yummy apple for the stackoverflow readers 1";
Fruit f2 = new Fruit();
f2.name = "Apple Ag";
f2.description = "Yummy yummy apple for the stackoverflow readers 2";
Fruit f3 = new Fruit();
f3.name = "Apple Mn";
f3.description = "Yummy yummy apple for the stackoverflow readers 3";
Fruit f4 = new Fruit();
f4.name = "Apple O2";
f4.description = "Yummy yummy apple for the stackoverflow readers 4";
//Evaluations for f1
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f1.evaluations.add(e);
}
//evaluations for f4
for (int i = 0; i < 4; i++) {
Evaluation e = new Evaluation();
e.id = i;
e.score = Math.random() * 10;
f4.evaluations.add(e);
}
fruits.add(f1);
fruits.add(f2);
fruits.add(f3);
fruits.add(f4);
return fruits;
}
public class Fruit {
public String name;
public String description;
public ArrayList<Evaluation> evaluations = new ArrayList<Evaluation>();
public Fruit() {
}
public Fruit(String name, String description) {
this.name = name;
this.description = description;
}
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;
}
public ArrayList<Evaluation> getEvaluations() {
return evaluations;
}
public void setEvaluations(ArrayList<Evaluation> evaluations) {
this.evaluations = evaluations;
}
}
public class Evaluation {
public int id;
public double score;
public Evaluation() {
}
public Evaluation(int id, double score) {
this.id = id;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
public class DataWrapper {
public String name;
public String description;
public Integer id;
public Double score;
public DataWrapper() {
}
public DataWrapper(String name, String description, Integer id, Double score) {
this.name = name;
this.description = description;
this.id = id;
this.score = score;
}
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;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
}
}
And here is the result:
Feel free to ask if you have some question.

How to store nested JSON Array into a Model

Hello so I have a model called Job. This model collects everything about a specific job. But the way the database relations are layed out means that when I return the job details I get a cargo array nested inside my job object. I want to know how I can store just the name inside the cargo array nested inside my JSON Object, I want to store it into my model.
Please may you take time to consider my situation, I have searched StackOverflow and other sites for a solution but the loops they provide aren't working. Hopefully I can find an answer by posting myself
JSON Object with nested Array:
"jobs": [
{
"id": 103080,
"user_id": 496,
"tracker_jobs_id": 91068,
"game_id": 1,
"pickup_city_id": 72,
"destination_city_id": 128,
"cargo_id": 366,
"pickup_company_id": 16,
"destination_company_id": 18,
"date": "2018-11-03",
"distance_driven": 244,
"load_damage": 7,
"estimated_income": 10956,
"total_income": 10956,
"cargo_weight": 24,
"division_load": 0,
"promotional_delivery_id": null,
"another_driver": 0,
"division_id": null,
"convoy_code": null,
"comments": null,
"created_at": "2018-11-04 00:24:42",
"updated_at": "2018-11-04 00:24:42",
"delete": "false",
"status": null,
"cargo": {
"id": 366,
"name": "Square Tubing",
"price_coef": 1,
"fragility": 0.2,
"wotr_only": 0,
"overweight_dlc": 0
},
.... (THEN IT LOOPS WITH THE NEXT JOB)
My Job Model:
public Job (int id, int user_id, int tracker_jobs_id, int game_id, int pickup_city_id, int destination_city_id,
int cargo_id, int pickup_company_id, int destination_company_id, Date date, int distance_driven, int load_damage,
int estimated_income, int total_income, int cargo_weight, int division_load, int promotional_devlivery_id, int another_driver,
int division_id, String convoy_code, String comments, String delete, String status, JSONArray cargo) {
this.id = id;
this.user_id = user_id;
this.tracker_jobs_id = tracker_jobs_id;
this.game_id = game_id;
this.pickup_city_id = pickup_city_id;
this.destination_city_id = destination_city_id;
this.cargo_id = cargo_id;
this.pickup_company_id = pickup_company_id;
this.destination_company_id = destination_company_id;
this.date = date;
this.distance_driven = distance_driven;
this.load_damage = load_damage;
this.estimated_income = estimated_income;
this.total_income = total_income;
this.cargo_weight = cargo_weight;
this.division_load = division_load;
this.promotional_devlivery_id = promotional_devlivery_id;
this.another_driver = another_driver;
this.division_id = division_id;
this.convoy_code = convoy_code;
this.comments = comments;
this.delete = delete;
this.status = status;
this.cargo = cargo;
}
As you can see I have already attempted storing it as a JSONArray but it ends up just being blank []
How I am storing it from my request:
JSONObject jObj = new JSONObject(response);
JSONArray listJobs = jObj.getJSONArray("jobs");
Gson gson = new Gson();
sUserJobs = new ArrayList<>();
for (int i = 0; i < listJobs.length(); i++) {
try {
Job job = gson.fromJson(listJobs.getJSONObject(i).toString(), Job.class);
sUserJobs.add(job);
} catch (JSONException e) {
e.printStackTrace();
}
}
You need to have a Cargo class as well. Then you need to extract cargo like below while getting Job class an set cargo object to relevant object as well.
Cargo cargo = gson.fromJson(listJobs.getJSONObject(i).getString("cargo").toString(), cargo.class);
change your Job model:
public class Job {
#SerializedName("id") // variable name from server
int id = 0;
#SerializedName("user_id")
int user_id = 0;
#SerializedName("tracker_jobs_id")
int tracker_jobs_id = 0;
#SerializedName("game_id")
int game_id = 0;
#SerializedName("pickup_city_id")
int pickup_city_id = 0;
#SerializedName("destination_city_id")
int destination_city_id = 0;
#SerializedName("cargo_id")
int cargo_id = 0;
#SerializedName("pickup_company_id")
int pickup_company_id = 0;
#SerializedName("destination_company_id")
int destination_company_id = 0;
#SerializedName("date")
String date = "";
#SerializedName("distance_driven")
int distance_driven = 0;
#SerializedName("load_damage")
int load_damage = 0;
#SerializedName("estimated_income")
int estimated_income = 0;
#SerializedName("total_income")
int total_income = 0;
#SerializedName("cargo_weight")
int cargo_weight = 0;
#SerializedName("division_load")
int division_load = 0;
#SerializedName("promotional_devlivery_id")
int promotional_devlivery_id = 0;
#SerializedName("another_driver")
int another_driver = 0;
#SerializedName("division_id")
int division_id = 0;
#SerializedName("convoy_code")
String convoy_code = "";
#SerializedName("comments")
String comments = "";
#SerializedName("delete")
String delete = "";
#SerializedName("status")
String status = "";
#SerializedName("cargo")
Cargo cargo = new Cargo();
public Job (int id, int user_id, int tracker_jobs_id, int game_id, int pickup_city_id, int destination_city_id,
int cargo_id, int pickup_company_id, int destination_company_id, String date, int distance_driven, int load_damage,
int estimated_income, int total_income, int cargo_weight, int division_load, int promotional_devlivery_id, int another_driver,
int division_id, String convoy_code, String comments, String delete, String status, Cargo cargo) {
this.id = id;
this.user_id = user_id;
this.tracker_jobs_id = tracker_jobs_id;
this.game_id = game_id;
this.pickup_city_id = pickup_city_id;
this.destination_city_id = destination_city_id;
this.cargo_id = cargo_id;
this.pickup_company_id = pickup_company_id;
this.destination_company_id = destination_company_id;
this.date = date;
this.distance_driven = distance_driven;
this.load_damage = load_damage;
this.estimated_income = estimated_income;
this.total_income = total_income;
this.cargo_weight = cargo_weight;
this.division_load = division_load;
this.promotional_devlivery_id = promotional_devlivery_id;
this.another_driver = another_driver;
this.division_id = division_id;
this.convoy_code = convoy_code;
this.comments = comments;
this.delete = delete;
this.status = status;
this.cargo = cargo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getTracker_jobs_id() {
return tracker_jobs_id;
}
public void setTracker_jobs_id(int tracker_jobs_id) {
this.tracker_jobs_id = tracker_jobs_id;
}
public int getGame_id() {
return game_id;
}
public void setGame_id(int game_id) {
this.game_id = game_id;
}
public int getPickup_city_id() {
return pickup_city_id;
}
public void setPickup_city_id(int pickup_city_id) {
this.pickup_city_id = pickup_city_id;
}
public int getDestination_city_id() {
return destination_city_id;
}
public void setDestination_city_id(int destination_city_id) {
this.destination_city_id = destination_city_id;
}
public int getCargo_id() {
return cargo_id;
}
public void setCargo_id(int cargo_id) {
this.cargo_id = cargo_id;
}
public int getPickup_company_id() {
return pickup_company_id;
}
public void setPickup_company_id(int pickup_company_id) {
this.pickup_company_id = pickup_company_id;
}
public int getDestination_company_id() {
return destination_company_id;
}
public void setDestination_company_id(int destination_company_id) {
this.destination_company_id = destination_company_id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getDistance_driven() {
return distance_driven;
}
public void setDistance_driven(int distance_driven) {
this.distance_driven = distance_driven;
}
public int getLoad_damage() {
return load_damage;
}
public void setLoad_damage(int load_damage) {
this.load_damage = load_damage;
}
public int getEstimated_income() {
return estimated_income;
}
public void setEstimated_income(int estimated_income) {
this.estimated_income = estimated_income;
}
public int getTotal_income() {
return total_income;
}
public void setTotal_income(int total_income) {
this.total_income = total_income;
}
public int getCargo_weight() {
return cargo_weight;
}
public void setCargo_weight(int cargo_weight) {
this.cargo_weight = cargo_weight;
}
public int getDivision_load() {
return division_load;
}
public void setDivision_load(int division_load) {
this.division_load = division_load;
}
public int getPromotional_devlivery_id() {
return promotional_devlivery_id;
}
public void setPromotional_devlivery_id(int promotional_devlivery_id) {
this.promotional_devlivery_id = promotional_devlivery_id;
}
public int getAnother_driver() {
return another_driver;
}
public void setAnother_driver(int another_driver) {
this.another_driver = another_driver;
}
public int getDivision_id() {
return division_id;
}
public void setDivision_id(int division_id) {
this.division_id = division_id;
}
public String getConvoy_code() {
return convoy_code;
}
public void setConvoy_code(String convoy_code) {
this.convoy_code = convoy_code;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getDelete() {
return delete;
}
public void setDelete(String delete) {
this.delete = delete;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<Cargo> getCargo() {
return cargo;
}
public void setCargo(List<Cargo> cargo) {
this.cargo = cargo;
}
}
and Create New Class named: Cargo
public class Cargo {
#SerializedName("id")
int id = 0;
#SerializedName("name")
String name = "";
#SerializedName("price_coef")
int price_coef = 0;
#SerializedName("fragility")
double fragility = 0.0;
#SerializedName("wotr_only")
int wotr_only = 0;
#SerializedName("overweight_dlc")
int overweight_dlc = 0;
public Cargo () {
}
public Cargo (int id, String name, int price_coef, double fragility, int wotr_only, int overweight_dlc) {
this.id = id;
this.name = name;
this.price_coef = price_coef;
this.fragility = fragility;
this.wotr_only = wotr_only;
this.overweight_dlc = overweight_dlc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice_coef() {
return price_coef;
}
public void setPrice_coef(int price_coef) {
this.price_coef = price_coef;
}
public double getFragility() {
return fragility;
}
public void setFragility(double fragility) {
this.fragility = fragility;
}
public int getWotr_only() {
return wotr_only;
}
public void setWotr_only(int wotr_only) {
this.wotr_only = wotr_only;
}
public int getOverweight_dlc() {
return overweight_dlc;
}
public void setOverweight_dlc(int overweight_dlc) {
this.overweight_dlc = overweight_dlc;
}
}
or.. you can post your json to this site and download your models:
http://www.jsonschema2pojo.org/
Target language: Java
Source type: JSON Schema or JSON
Annotation style: Gson

Return more that one ArrayList

I'm trying to deal with this baking JSON:
in android app so this is the class to bring the JSON data from link:
OpenBakingJsonUtils.java:
public final class OpenBakingJsonUtils {
public static ArrayList<ArraysLists> getSimpleBakingStringsFromJson(Context context, String bakingJsonString)
throws JSONException {
final String ID = "id";
final String NAME = "name";
final String SERVINGS = "servings";
final String INGREDIENTS = "ingredients";
final String STEPS = "steps";
final String QUANTITY = "quantity";
final String MEASURE = "measure";
final String INGREDIENT = "ingredient";
final String IDSTEPS = "id";
final String SHORTDESCRIPTION = "shortDescription";
final String DESCRIPTION = "description";
final String VIDEOURL = "videoURL";
final String THUMBNAILURL = "thumbnailURL";
ArrayList<ArraysLists> parsedRecipeData = new ArrayList<ArraysLists>();
ArrayList<BakingItem> Baking = new ArrayList<BakingItem>();
JSONArray recipeArray = new JSONArray(bakingJsonString);
for (int i = 0; i < recipeArray.length(); i++) {
int id;
String name;
int servings;
double quantity;
String measure;
String ingredient;
int idSteps;
String shortDescription;
String description;
String videoURL;
String thumbnailURL;
JSONObject recipeObject = recipeArray.getJSONObject(i);
id = recipeObject.getInt(ID);
name = recipeObject.getString(NAME);
servings = recipeObject.getInt(SERVINGS);
ArrayList<IngredientsItem> Ingredients = new ArrayList<IngredientsItem>();
JSONArray ingredientsArray = recipeObject.getJSONArray(INGREDIENTS);
for(int j = 0 ; j< ingredientsArray.length(); j++) {
JSONObject ingredientsObject = ingredientsArray.getJSONObject(j);
quantity = ingredientsObject.getDouble(QUANTITY);
measure = ingredientsObject.getString(MEASURE);
ingredient = ingredientsObject.getString(INGREDIENT);
Ingredients.add(new IngredientsItem(quantity, measure, ingredient));
}
ArrayList<StepsItem> Steps = new ArrayList<StepsItem>();
JSONArray stepsArray = recipeObject.getJSONArray(STEPS);
for(int j = 0 ; j< stepsArray.length(); j++) {
JSONObject stepsObject = stepsArray.getJSONObject(j);
idSteps = recipeObject.getInt(IDSTEPS);
shortDescription = stepsObject.getString(SHORTDESCRIPTION);
description = stepsObject.getString(DESCRIPTION);
videoURL = stepsObject.getString(VIDEOURL);
thumbnailURL = stepsObject.getString(THUMBNAILURL);
Steps.add(new StepsItem(idSteps, shortDescription, description, videoURL, thumbnailURL));
}
Baking.add(new BakingItem(id, name, servings, Ingredients, Steps));
parsedRecipeData.add(new ArraysLists(Baking, Ingredients, Steps));
}
return parsedRecipeData;
}
}
as you see there are 3 ArrayList classes:
ArrayList<BakingItem>
ArrayList<IngredientsItem>
ArrayList<StepsItem>
and this is the code for each one:
BakingItem.java:
public class BakingItem implements Parcelable {
private int id;
private String name;
private int servings;
private ArrayList<IngredientsItem> ingredients = new ArrayList<IngredientsItem>();
private ArrayList<StepsItem> steps = new ArrayList<StepsItem>();
public BakingItem(int id, String name, int servings, ArrayList<IngredientsItem> ingredients, ArrayList<StepsItem> steps) {
this.id = id;
this.name = name;
this.servings = servings;
this.ingredients = ingredients;
this.steps = steps;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(name);
out.writeInt(servings);
out.writeTypedList(ingredients);
out.writeTypedList(steps);
}
private BakingItem(Parcel in) {
this.id = in.readInt();
this.name = in.readString();
this.servings = in.readInt();
ingredients = new ArrayList<IngredientsItem>();
in.readTypedList(ingredients, IngredientsItem.CREATOR);
}
public BakingItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<BakingItem> CREATOR = new Parcelable.Creator<BakingItem>() {
#Override
public BakingItem createFromParcel(Parcel in) {
return new BakingItem(in);
}
#Override
public BakingItem[] newArray(int i) {
return new BakingItem[i];
}
};
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getServings() {
return servings;
}
}
IngredientsItem.java:
public class IngredientsItem implements Parcelable {
private double quantity;
private String measure;
private String ingredient;
public IngredientsItem(double quantity, String measure, String ingredient) {
this.quantity = quantity;
this.measure = measure;
this.ingredient = ingredient;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeDouble(quantity);
out.writeString(measure);
out.writeString(ingredient);
}
private IngredientsItem(Parcel in) {
this.quantity = in.readDouble();
this.measure = in.readString();
this.ingredient = in.readString();
}
public IngredientsItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<IngredientsItem> CREATOR = new Parcelable.Creator<IngredientsItem>() {
#Override
public IngredientsItem createFromParcel(Parcel in) {
return new IngredientsItem(in);
}
#Override
public IngredientsItem[] newArray(int i) {
return new IngredientsItem[i];
}
};
public double getQuantity() {
return quantity;
}
public String getMeasure() {
return measure;
}
public String getIngredient() {
return ingredient;
}
}
as well as the StepsItem class
and the forth is the ArraysLists.java which contain all the 3 arrays above and returned by the OpenBakingJsonUtils.java:
Then I'm trying to call these JSON data in different activities
so in MainActivity.java in loadInBackground:
Override
public ArrayList<BakingItem> loadInBackground() {
URL recipeRequestUrl = NetworkUtils.buildUrl();
try {
String jsonBakingResponse = NetworkUtils.getResponseFromHttpUrl(recipeRequestUrl);
ArrayList<ArraysLists> simpleJsonBakingData = OpenBakingJsonUtils.getSimpleBakingStringsFromJson(MainActivity.this, jsonBakingResponse);
return simpleJsonBakingData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I call the returned ArrayList from OpenBakingJsonUtils.java which is in this case the ArraysLists,
then in DetailActivity.java in doInBackground:
#Override
protected ArrayList<ArraysLists> doInBackground(Object... params) {
if (params.length == 0) {
return null;
}
URL reviewsRequestUrl = NetworkUtils.buildUrl();
try {
String jsonReviewResponse = NetworkUtils.getResponseFromHttpUrl(reviewsRequestUrl);
ArrayList<ArraysLists> simpleJsonReviewData = OpenBakingJsonUtils.getSimpleBakingStringsFromJson(DetailsActivity.this, jsonReviewResponse);
return simpleJsonReviewData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
here I call the ArrayList of ArraysLists too but the problem in adapters of MainActivity.java and DetailsActivity.java in onBindViewHolder:
holder.CommentContent.setText(String.valueOf(mCommentsItems.get(position).getQuantity()));
it just says that cannot resolve method getQuantity() which is in IngredientsItem.java while I used the ArraysLists.java that returned by OpenBakingJsonUtils.java
so what should I do to call methods from BakingItem.java and IngredientsItem.java while I use the returned ArraysLists.java ?

Count instances in constructor

In my EMR Class, I am trying increment the patient counter data field after my constructor with 2 variables. I am also trying to increment the patient counter datafield after my construct with 5 variables.
In the Main the end goal is to Create 5 new patient records (which I did) and Print the number of patient records available before and after.
I am pretty sure I have to use public static long numofpatients in my EMR class, but don't know where to go from there.
Main code:
package studenthealthservices;
public class Studenthealthservices {
public static void main(String[] args) {
EMR p1 = new EMR("Colin", "10-22-74", "Strained Ankle", 99, 110, "hurt during football", "ankle brace");
System.out.println(p1.toString());
EMR p2 = new EMR("Anquan", "9-30-77", "stomach ache", 98, 120, "stress", "Tylenol");
System.out.println(p2.toString());
EMR p3 = new EMR("Buster", "3-27-1987", "Broken ankle", 99, 113, "Scott Cousins", "None");
System.out.println(p3.toString());
EMR P4 = new EMR("Frank The Tank", "4/1/89");
EMR p5 = new EMR("Merton Hanks", "03-12-1968");
}
}
EMR class code:
package studenthealthservices;
public class EMR {
private String name;
private String dob;
private String rfv;
private double bodyt;
private double hr;
private String diag;
private String pmeds;
public void setName(String name) {
this.name = name;
}
public EMR(String name, String dob) {
this.name = name;
this.dob = dob;
}
public String getName() {
return name;
}
public EMR(String name, String dob, String rfv, double bodyt, double hr, String diag, String pmeds) {
this.name = name;
this.dob = dob;
this.rfv = rfv;
this.bodyt = bodyt;
this.hr = hr;
this.diag = diag;
this.pmeds = pmeds;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getRfv() {
return rfv;
}
public void setRfv(String rfv) {
this.rfv = rfv;
}
public double getBodyt() {
return bodyt;
}
public void setBodyt(double bodyt) {
this.bodyt = bodyt;
}
public double getHr() {
return hr;
}
public void setHr(double hr) {
this.hr = hr;
}
public String getDiag() {
return diag;
}
public void setDiag(String diag) {
this.diag = diag;
}
public String getPmeds() {
return pmeds;
}
public void setPmeds(String pmeds) {
this.pmeds = pmeds;
}
public void redFlags() {
String help = "get help!";
if (bodyt >= 97.3 && bodyt <= 99.1)
this.bodyt = bodyt;
if (hr >= 60 && hr <= 100)
this.hr = hr;
else {
System.out.printf(help);
}
}
#Override
public String toString() {
return "\nname : " + this.name
+ "\nDate of Birth: " + this.dob
+ "\nReason for visit: " + this.rfv
+ "\nBody Temperature: " + this.bodyt
+ "\nHeart Rate " + this.hr
+ "\nDiagnosis: " + this.diag
+ "\nPrescribed Meds " + this.pmeds;
}
}
I would avoid incrementing a static variable in the constructor, and instead push that responsibility into the StudentHealthServices class, like this:
public class StudentHealthServices {
private int numOfPatients;
public static void main(String[] args) {
StudentHealthServices services = new StudentHealthServices();
EMR p1 = new EMR("Colin", "10-22-74", "Strained Ankle", 99, 110, "hurt during football", "ankle brace");
services.add(p1);
EMR p2 = new EMR("Anquan", "9-30-77", "stomach ache", 98, 120, "stress", "Tylenol");
services.add(p2);
EMR p3 = new EMR("Buster", "3-27-1987", "Broken ankle", 99, 113, "Scott Cousins", "None");
services.add(p3);
EMR p4 = new EMR("Frank The Tank", "4/1/89");
services.add(p4);
EMR p5 = new EMR("Merton Hanks", "03-12-1968");
services.add(p5);
}
private void add(EMR emr) {
// maybe you want to store the patients in a list here?
System.out.println(emr);
System.out.println("there are now " + ++numOfPatients + " patients");
}
}
see here (simplified your class):
package studenthealthservices;
public class EMR
{
private static /*volatile*/ long numofpatients; // when using different threads, volatile is needed.
private String name;
private String dob;
public EMR(String name, String dob) {
numofpatients++; //increment here
this.name = name;
this.dob = dob;
}
public EMR(String name, String dob, String rfv, double bodyt, double hr, String diag, String pmeds) {
numofpatients++; //increment here
this.name = name;
this.dob = dob;
//simplified
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
#Override
public String toString() {
return "simplified";
}
public static long getInstanceCount()
{
return numofpatients;
}
}

Categories