Passing objects as parameters in SugarORM - java

I have an object extending SugarRecord that looks like this:
public class SavedDraft extends SugarRecord {
private String name;
private String difficulty;
private int sport_id;
private LocalActivity localActivity;
public SavedDraft() {
}
public SavedDraft(String name, String difficulty, int ID, LocalActivity localActivity) {
this.name = name;
this.difficulty = difficulty;
this.sport_id = ID;
this.localActivity = localActivity;
}
}
The problem is that I always get a null object when I try to get the localActivity object from the database (see: SavedDraft.findById(SavedDraft.class, 1).getLocalActivity()), and I'm just wondering if it's possible to save objects as parameters in SugarORM at all.

This would be a relationship and you would need the LocalActivity to extend SugarRecord also.
See the documentation of Book and Author: http://satyan.github.io/sugar/creation.html

Related

How may I convert java custom Object to String and back again

I would like to write a converter to convert my custom object to DTO and back. How do I approach it?
I have 2 classes Appointment and Doctor which is a subclass of Appointment. I would like to have the converter as simple as possible.
I am not looking for straight answer, would appreciate tips on how to approach it.
below classes have getters and setters:
public class Doctor {
private long id;
private String name;
private String surname;
private String key;
}
public class Appointment {
private long id;
private String description;
private Doctor doctor;
private Date appointmentDate;
}
//converter
public class ConverterComponent {
public AppointmentDTO convert(Appointment appointment){
AppointmentDTO appointmentDTO = new AppointmentDTO();
appointmentDTO.id = appointment.getId();
appointmentDTO.description = appointment.getDescription();
appointmentDTO.doctor = appointment.getDoctor().toString();
appointmentDTO.appointmentDate = appointment.getAppointmentDate().toString();
return appointmentDTO;
}
}
I would like to write another convert(AppointmentDTO appointmentDTO) method in ConverterComponent which will return the Appointment object back.
Could it be done just by parsing Object to json and back again?
Thanks,

PUT request with JSON payload sent from Postman, nested object not parsed

I didn't have this problem before, with other POJOs, I'm not sure what's different this time, but I can't get this working and I could not find an exact solution for this.
I have this POJO called Component (with some Hibernate annotations):
#Entity
#Table(name="component", uniqueConstraints={#UniqueConstraint(
columnNames = {"name", "component_type"})})
public class Component {
#Column(name="id")
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="name")
private String name;
#Column(name="component_type")
private String componentType;
#Column(name="serial_number")
private int serialNumber;
#Column(name="active_since")
private String activeSince;
#Embedded
private ComponentWearoutModel wearout;
public Component() {
}
public Component(String name, String componentType, int serialNumber, String activeSince,
ComponentWearoutModel wearout) {
this.name = name;
this.componentType = componentType;
this.serialNumber = serialNumber;
this.activeSince = activeSince;
this.wearout = wearout;
}
public ComponentWearoutModel getModel() {
return wearout;
}
public void setModel(ComponentWearoutModel wearout) {
this.wearout = wearout;
}
//more getters and setters
}
ComponentWearoutModel:
#Embeddable
public class ComponentWearoutModel {
private String componentType; //dont mind the stupid duplicate attribute
private Integer componentLifeExpectancy;
private Float componentWearOutLevel;
private Float actionThreshold;
public ComponentWearoutModel() {
}
public ComponentWearoutModel(String componentType, int componentLifeExpectancy, float componentWearOutLevel,
float actionThreshold) {
this.componentType = componentType;
this.componentLifeExpectancy = componentLifeExpectancy;
this.componentWearOutLevel = componentWearOutLevel;
this.actionThreshold = actionThreshold;
}
//getters and setters
}
The sample payload I use:
{
"name": "component name",
"componentType": "airfilter2",
"serialNumber": 573224,
"activeSince": "2016-04-10 17:38:41",
"wearout":
{
"componentType": "airfilter",
"componentLifeExpectancy": 1000,
"componentWearOutLevel": 0.24,
"actionThreshold": 0.2
}
}
And finally the resource class:
#Path("myresource")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public class MyResource {
DatabaseManager dm = DatabaseManager.getInstance();
#PUT
#Path("Component")
public Response storeComponent(Component component){
System.out.println("reached");
System.out.println(component.getComponentType()); //okay
System.out.println(component.getModel().getComponentType()); //nullpointerexception
ComponentWearoutModel model = new ComponentWearoutModel("type", 1000, 1f, 0.2f);
component.setModel(model); //this way it's saved in the db just fine
dm.save(component);
return Response.status(Status.OK).entity(component).build();
}
}
Without the prints, only the fields which are not part of the ComponentWearoutModel class are stored in the database table, the other columns are null. So when I try to print one of them, I get an exception, I just dont understand why. If I create a ComponentWearoutModel in the resource method and add it to the component, everything is fine in the database.
UPDATE:
so my mistake was that I named the ComponentWearoutModel attribute as "wearout" in the Component.class, but the autogenerated getters and setter were called getModel/setModel and moxy could not parse my payload because of this. Solution: change the attribute name to "model" in Component class and in payload too.
Please ensure that the attribute names you are using in the POJO are same as what are being sent in the json string.
Since there are no jackson etc annotations being used in your POJO to tell it the corresponding json mapping, the underlying code will directly use the names given in json string. If you are using the string "model", the convertor code will look for a "setModel" method in your POJO.
In the above example, either call everything "model", or "wearable".

How can I get the class object from its member variable?

I'm currently working on this code, I want to pass an ID to a member function to get the object.
public class Car {
private int _ID;
private String name;
private String model;
Car(int _id, String name, String model){
this._ID = _id;
this.name = name;
this.model = model;
}
....
public static Car getCar(int _id){
Car mCar;
//TODO: Algo to get car
return mCar;
}
}
Is there any way I can get the object in this way?
Any help is appreciated!
Thank You!
You'll need to keep a Map of objects by key. Here's one way to do it:
public class Car {
private int _ID;
private String name;
private String model;
Car(int _id, String name, String model){
this._ID = _id;
this.name = name;
this.model = model;
carsById.put(_id, this); // <-- add to map
}
....
private static Map<Integer, Car> carsById = new HashMap<>();
public static Car getCar(int _id){
return carsById.get(_id);
}
}
There's no predefined way to do that. You'd have to have Car or something else maintain a Map<Integer,Car> or similar of cars. This would usually be best done not in Car itself, but in the code using it.
Unless you have a list (or map or tree or anything else suitable) of created Car, it's not possible with your current code only. A good practice is to separate this list out of Car class, maintained elsewhere. But if you insist, shmosel provides one way.

Adding data to an array list

I'm working on an Android project and I'm trying to make use of an ArrayList which is of type MyClass. I am trying to store data in the ArrayList to each of the variables within MyClass. Below is the code I am using.
Below is the Class with the variables that will be used.
class SearchData
{
public int id;
public String category;
public String company;
public String loginAction;
public String username;
public String password;
public String type;
public String appName;
}
Below is how I am initialising the ArrayList
ArrayList<SearchData> passwords = new ArrayList<SearchData>();
And below is how I am trying to add new data to the ArrayList
passwords.add(new SearchData()
{
});
I can't figure out how to then set the variables from within the class with the data that I need them to be set to. In C#, which I know more about than Java, I can do the following:
passwords.add(new SearchData()
{
id = 0,
category = "hello"
});
However, I'm not seeing any of the variables that are within the class being shown in the Intellisense help.
What am I doing wrong?
You need to create an object and set all the attributes first, and then add it to the List: -
SearchData searchData = new SearchData();
searchData.setId(1);
searchData.setCategory(category);
...
passwords.add(searchData);
Create a constructor for your class.
class SearchData
{
public int id;
public String category;
public String company;
public String loginAction;
public String username;
public String password;
public String type;
public String appName;
SearchData(int id, String category, String company......){
this.id = id;
this.category = category;
this.company = company;
...
}
}
Then use it like this:
passwords.add(new SearchData(0,"Category1", "Company1"......));
Create an object and store reference to it:
SeachData searchData = new SearchData();
Set the properties you want to set:
searchData.setId(123);
...so on
searchData. Ctrl+Space should show the intellisense now..
Adding the search reference to the list:
list.add(searchData);
SearchData sd = new SearchData();
sd.id = 0;
sd.category = "hello";
passwords.add(sd);

How to refer to an inner class inside a list in Java

after messing around with parsing a JSON response with GSON for a day, I finally figured out how to get my javabeans right in order to extract my data from the response. This is the layout of my nested classes and lists:
public class LocationContainer {
public class paging {
private String previous;
private String next;
}
private List<Datas> data;
public class Datas {
private String message;
private String id;
private String created_time;
public class Tags {
private List<Data> datas;
public class Data {
private String id;
private String name;
}
}
public class Application {
private String id;
private String name;
}
public class From {
private String id;
private String name;
}
public class Place {
private String id;
private String name;
public class Location {
private int longitude;
private int latitude;
}
}
}
}
Now I am trying to get a hold of the name string inside the place class and the created_time string, but since I am quite a noob, I can't seem to figure it out.
I was able to extract the created_time string by using
String time = gson.toJson(item.data.get(1).created_time);
However using
String name = gson.toJson(item.data.get(1).Place.name);
doesnt work.
The item class is an instance of LocationContainer filled with the output from GSON.
Any pointers would be greatly appreciated.
created_time is a member variable of Data, so your first line is fine.
However, Place is not a member variable, it's just a class definition. You probably need to instantiate a member variable inside your Data class, e.g.:
private Place place;

Categories

Resources