Not able to parse fields with underscores - java

I have a column name viewed_by on Firebase server
Test
|
|--viewed_by: 30
On the app I have a POJO class which has the member viewed_by
Test.class has member
private int viewed_by;
In onDataChange function when I receive the data, I get the Test object using the getValue function
Test t = dataSnapshot.getValue(Test.class);
But I get the value as 0 instead of 30.
If I change the field name from viewed_by to viewedBy (both on server and POJO class), I get the expected value (30)
Is it a parsing issue in getValue function? Or the field name are not supposed to have underscores in the name?

Jus figured it out, had to change the function names as well from ViewedBy to Viewed_By for it to work with viewed_by field
/**
*
* #return
* The viewed_by
*/
public int getViewed_By() {
return viewed_by;
}
/**
*
* #param viewed_by
* The viewed_by
*/
public void setViewed_By(int viewed_by) {
this.viewed_by = viewed_by;
}

Another option is to just declare the properties like below-using #PropertyName("property_name") in your model and use your getter and setter just like you like to do.
public class Actor {
#NonNull
#PrimaryKey
#ColumnInfo(name = "profile_id")
#PropertyName("profile_id")
private String profileId;
#ColumnInfo(name = "name")
#PropertyName("name")
private String name;
#PropertyName("profile_id")
public String getProfileId() {
return profileId;
}
#PropertyName("profile_id")
public void setProfileId(String profileId) {
this.profileId = profileId;
}
#PropertyName("name")
public String getName() {
return name;
}
}

Related

how to get name value associated with integer in dto

i'm using java, for example, i have 2 tables staff(id, name, status_id, company_id) and company(id, name), the corresponding entity looks like:
public class Staff {
private Integer id;
private String name;
private Integer statusId;
private Integer companyId;
private Company company;
}
public class Company {
private Integer id;
private String name;
private List<Staff> staffList;
}
for status_id of table staff, 0 means New, 1 represents Active and 2 stands for Inactive.
I need to show New, Active or Inactive on html page/excel when describe a staff status rather than 0, 1 or 2.
And I have a StaffDto:
public class StaffDto {
private Integer id;
private String name;
private Integer statusId;
private String companyName;
}
my questions are:
the statusName(New/Active/Inactive) should be in StaffDto, such that there is no need to calculate status name according to statusId on each client, right?
what is a good practice to get statusName base on statusId?
I should write code like
public class StaffDto {
private Integer statusId;
private String statusName;
public String getStatusName() {
switch(statusId) {
case 0: return "New";
case 1: return "Active";
case 2: return "Inactive";
}
}
}
is this a good practice? or something else(e.g. enum) is better?
if the logic of getting status name is added in StaffDto, what if there is another dtoj(e.g. ADto) also need to show status name, then I have to re-write this logic in ADto?
what if one client need to show New, Active or Inactive, while another client need to show A, B or C or something else, then what should I return in StaffDto? do I still return New, Active or Inactive in StaffDto, and other client need to calculate N, A or I base on statusId on their client? or should I return something else to client instead of xxxDto?
I too would go for enum as you mentioned, bind the status code to the name
then, you do not have to rewrite the logic in DTOs, Make your model have the enum rather than code or name
enum can have its own methods like getShortName for different representations
enum Status {
NEW(0), Active(1), InActive(2);
private final int code;
Status(int code) {
this.code = code;
}
public String getShortName() {
return this.name().substring(0, 1).toUpperCase();
}
public int getCode() {
return code;
}
}

Passing objects as parameters in SugarORM

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

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".

java OOP link between classes (first time programming in java)

I would like to link two classes where the consultant have an ID and I would like to send this ID to the customer so a customer will be assigned to the consultant.
I created a class for the consultant with the ID, name and surname and the same for the customer. I am trying to get the ID from the consultant using the code below
Consultant newconsultant = new Consultant(Consultant.getConsultantID());
The consultantID is the id of the consultant in the class consultant.I am stuck and I appreciate any help with any information for this issue.
Consultant code:
public class Consultant extends Person implements Serializable {
public String ConsultantID;
private String Consfirstname;
private String Conslastname;
Consultant(String consultantID) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* #return the ConsultantID
*/
public String getConsultantID() {
return ConsultantID;
}
/**
* #param ConsultantID the ConsultantID to set
*/
public void setConsultantID(String ConsultantID) {
this.ConsultantID = ConsultantID;
}
/**
* #return the Consfirstname
*/
public String getConsfirstname() {
return Consfirstname;
}
/**
* #param Consfirstname the Consfirstname to set
*/
public void setConsfirstname(String Consfirstname) {
this.Consfirstname = Consfirstname;
}
/**
* #return the Conslastname
*/
public String getConslastname() {
return Conslastname;
}
/**
* #param Conslastname the Conslastname to set
*/
public void setConslastname(String Conslastname) {
this.Conslastname = Conslastname;
}
Customers Code:
public class Customer extends Person implements Serializable {
private String CustomerID;
public String Custfirstname;
public String Custlastname;
private Consultant Consultant;
public String CID;
Consultant newconsultant = new Consultant(Consultant.getConsultantID());
/**
* #return the CustomerID
*/
public String getCustomerID() {
return CustomerID;
}
/**
* #param CustomerID the CustomerID to set
*/
public void setCustomerID(String CustomerID) {
this.CustomerID = CustomerID;
}
/**
* #return the Custfirstname
*/
public String getCustfirstname() {
return Custfirstname;
}
/**
* #param Custfirstname the Custfirstname to set
*/
public void setCustfirstname(String Custfirstname) {
this.Custfirstname = Custfirstname;
}
/**
* #return the Custlastname
*/
public String getCustlastname() {
return Custlastname;
}
/**
* #param Custlastname the Custlastname to set
*/
public void setCustlastname(String Custlastname) {
this.Custlastname = Custlastname;
}
/**
* #return the Consultant
*/
public Consultant getConsultant() {
return Consultant;
}
/**
* #param Consultant the Consultant to set
*/
public void setConsultant(Consultant Consultant) {
this.Consultant = Consultant;
}
/**
* #return the CID
*/
public String getCID() {
return CID;
}
/**
* #param CID the CID to set
*/
public void setCID(String CID) {
this.CID = CID;
}
There are two forms were the consultant and customers details will be inputted.
In your Customer class are using Consultant class incorrectly.
You are trying to access a non-static method in a static way.
It is not clear if you have getter and setter methods then why you are trying to create a Consultant instance saperately. This looks to be incrrect in design perspective
What you can do is:
From a another class say MyApplication you can first set Consultant and using the same object you can pass it to Customer.
Consultant consultant = new Consultant("123");
consultant.setConsultantID("123");
consultant.setConsfirstname("firstname");
consultant.setConslastname("lastname");
Customer customer = new Customer();
customer.setConsultant(consultant);
This way your customer instance will have a reference to a Consultant instance in it with all the details. This is has-a relationship also called as a composition.
You are calling getConsultatntId in a static way. If your variable is not static you should call the method from a instance of the object (instead of the Class name)
That would look like:
Consumer c = new Consumer(1000);
Consultant con = new Consultant(c.getConsumerId());
Note that I'm calling getId from 'c' that is a instance of Consumer.
Firstly, you should make your Consultant constructor public. Secondly, you cannot access a non-static method in a static way, meaning you need to make a public static String getConsultantID() or something like this:
Consultant c = new Consultant("c2418");
Consultant d = new Consultant(c.getConsultantID());
Two things:
1:
To give a customer a consultant id, you would use an instance method instead of a static method:
Consultant james = new Consultant("123");
Customer customer1 = new Customer(james.getConsultantId());
2:
Consider using an Array or List of Customers in the Consultant class. It would seem more appropriate for a consultant to have multiple customers, rather than a single Consultant to Client relationship. In this way, you create a one-to-many relationship between Consultants and Customers.
Customers would have a reference to their Consultant, and Consultants would have a reference to all of their Customers.
public class Consultant extends Person implements Serializable {
public String ConsultantID;
private String Consfirstname;
private String Conslastname;
private ArrayList<Customer> customers;
Consultant(String consultantID) {
customers = new ArrayList();
}
public boolean addCustomer(Customer c){
customers.add(c);
}
//snipped for brevity
}
public class Customer extends Person implements Serializable {
private String CustomerID;
public String Custfirstname;
public String Custlastname;
public String CID;
Customer(Consultant c){
CID = c.getConsultantID();
}
//snipped for brevity
}
When you create the relationship, you'd create the customer first, assign them a consultant, then add the customer to the Consultant.
Consultant kingston = new Consultant("kingston88"); //created elsewhere
Customer jack = new Customer(kingston); //create customer, give id
kingston.add(jack); //assign customer to consultant

How can I grab an item from a collection in a serializable class?

I have something like this(Very simplified version):
public class TransferData implements Serializable{
private Collection[] collections;
private String ID;
public TransferData( Collection[] collections){
this.ID = ID;
this.collections = collections;
}
public String getID(){
return ID;
}
public Collection[] getCollections(){
return collections;
}
}
This is how I usually grab an item:
//Save object in db
ContentValues values = new ContentValues();
values.put("id", td.getID());
However, I am having trouble understanding how to grab an item from a collection/array in a serializable class?
This doesn't make sense:
ContentValues values = new ContentValues();
values.put("collectionitem1", td.getCollections()); ??? //need to index the array, how?
I tried something like this:
for (int i=0; i <= td.getCollections().length; i++) {
System.out.println(i);
}
but strangely only gives me 3 indices instead of 4 indices that I have in my array but it doesn't help me. Also, my array contains strings and integers, so might be hard to index through with a foreach style loop.
Figured it out! I knew it was something about setting up going through the array incorrectly. Here's the solution:
//Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
for (Collection collection : td.getCollections()) {
values.put("reminders", collection.getNumberOfReminders());
}
I see you're using SQLite. It seems to me that you're going about this all wrong. It seems like you need to use Entity Classes:
/**
*
* #author kkennedy
*/
#Entity(name = "TransferData")
#Table(name = "TransferData")
public class TransferData implements Serializable {
#Id
#Basic(optional = false)
#Column(name = "ID", nullable = false, length = 8)
private String ID;
#Basic(optional = false)
#Column(name = "data", nullable = false, length = 8)
private String data;
/**
* Default Constructor
*/
public TransferData() {
}
/**
* Getter
*
* #return
*/
public String getID() {
return ID;
}
/**
* Setter
*
* #param ID
*/
public void setID(String ID) {
this.ID = ID;
}
/**
* Getter
*
* #return
*/
public String getData() {
return data;
}
/**
* Setter
*
* #param data
*/
public void setData(String data) {
this.data = data;
}
}
I'm sure this is not what you would actually use, but by using Entity Classes, the JDBC driver does all the work of actually putting the data into and out of the database. You just enter it into the class and then persist and query the database, as needed.
Not sure if this is the best place to start, but try here for more info: http://docs.oracle.com/javaee/5/tutorial/doc/bnbqw.html

Categories

Resources