In the past I have had no problems serializing and deserializing POJOs using GSon library. But ever since I modularization my project and updated my Android studio to 4.1, any POJO I try to serialize returns me a bad value here is an example.
The expected result
dSecBook.toString ==> DSecBook{sd='for the love of God and I not e', np='26.5', op='null', img='null', id='null'}
the result I'm getting
dSecBook.toJSon ==> {"b":"for the love of God and I not e","c":"26.5"}
Here is my POJO which is an SQL query derivative
public class DSecBook implements Serializable {
#ColumnInfo(name = "short_description")
public String sd;
#ColumnInfo(name = "newPrice")
public String np;
#ColumnInfo(name = "oldPrice")
public String op;
#ColumnInfo(name = "pro_download_thumbUrl")
public String img;
#ColumnInfo(name = "proID")
public String id;
public DSecBook() {
//for firebase
}
public DSecBook(String sd, String np, String op, String img, String id) {
this.sd = sd;
this.np = np;
this.op = op;
this.img = img;
this.id = id;
}
........
}
Problem is even firebase is giving the same result, this is killing my work
Please help
Related
I am trying to save a base64 value into my sqlite database using Room and for some reason it's not saving. Well, i'm assuming it's not saving because when I try to read the table that has the base64 column, it returns values for all the other columns except the base64 column. What am I doing wrong?
My Entity:
#Entity(tableName = "healthCareWorkerInformation",
foreignKeys = #ForeignKey(
entity = HealthCareWorker.class,
parentColumns = {"id"},
childColumns = {"hcwId"},
onDelete = ForeignKey.CASCADE),
indices = #Index(
value = {"hcwId"}))
public class HealthCareWorkersInformation {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "hcwInfoId")
private long id;
private long hcwId;
//#ColumnInfo(typeAffinity = ColumnInfo.BLOB)
private String base64Image;
private String updatedAt = new SimpleDateFormat("dd MM yyyy, HH:mm",
Locale.getDefault()).format(Calendar.getInstance().getTime());
public HealthCareWorkersInformation() {
}
#Ignore
public HealthCareWorkersInformation(long hcwId) {
this.hcwId = hcwId;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getHcwId() {
return hcwId;
}
public void setHcwId(long hcwId) {
this.hcwId = hcwId;
}
public String getBase64Image() {
return base64Image;
}
public void setBase64Image(String base64Image) {
this.base64Image = base64Image;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
}
My DAO:
#Insert
void insertHealthCareWorkerInformation(HealthCareWorkersInformation healthCareWorkersInformation);
#Query("SELECT * FROM HEALTHCAREWORKERINFORMATION")
LiveData<List<HealthCareWorkerInformation>> getHCWInfo();
Sample data I send through:
{"consentGiven":null,"hcwId":1,"patiendId":1,"name":"Ben","lastName":"Ben","dateOfBirth":"4/9/2019","phoneNumber":"+271234567","base64Image":"data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAGQASwDASIAAhEBAxEB/8QAHgAAAgEFAQEBAAAAAAAAAAAAAgMEAAEFBgcICQr/xABSEAACAQIEAwUGAwYDBAYHCAMBAhEDIQAEEjEFQVEGEyJhcQeBkaGx8AgywRQjQtHh8QkVUhYXM2IKGCQlQ4I0NVNjcpKiGSZEVHODlLOjstT/xAAcAQADAAMBAQEAAAAAAAAAAAABAgMABAYFBwj/xAA6EQABAwIEAgYJAgYDAQAAAAABAAIRAyEEEjFBBVEGEyJhkaEUFTJCUnGBwdGx8AczQ4LC8RYjJFP/2gAMAwEAAhEDEQA/APn4stpu5P5ove17/wBsNpVCaqKSph9Ji1xb79ThLMaKtrqAQLrG4j19/wCuGy6AWbSwHiHNuR+X3GN7qyQtAO2CcrjSrhdJMEyLx8fX4YZQd6FmVgFJWZ8IIi+17TOEqRrDEEd4ATPLe219vmcMmAAqkLBnxbi3X7+GJxBvoUoqCcyyfAXSjxvJd4RoGYQkRsJGrc3EE4jrUNenTVjq0rMNeTeQQB6/ewqulww1kAgyYgnebctsSOPZRctxjOU6IbuqeZ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1CN9vf8Yta+L1GUnSATMEgCQ3MDf7+WFrS8KeIu+uCZuDO3reMYBus6wgQdFeqoesgf95LSBpJIsYN+d/ngtRqoRqKlWMaZgCQbn34UKhrZkyxEiVBIA57fKfdgqY0UwQz2FmjrEn7/AFwpaUAQXdxQXWpqYFXZYki4AtvsYv5YoVYdlU09QAFjFzM+fL5YCqVqp+7puAAQTGnTy5bjzxThnpFCQxMgiALR87zOCW3lEOTlbWg1srFSVLdb3m28+WL0n7qowUaZEmRpPL0Bt064SlZ97+M6vE0GIv7p9d/hRrGkDLmUW4U2G0z5b7/2wgzGqJAF08Or1KisYUjSADus2tHp5+/DBUNJID01ggMzGJMiAbRyj+8YXSpaWVJk6ZB6nz8/rOAMU0aoq3AiIuR0vz914wDJdCME2Te8UqxANiN7CNM4RQr0qjaSBYQFnSBY38vvpgxpcvLaHBEEHSN4gTa4PrfCKxCsJ1K3kd+vx6YzKNFMEi6u9Ukggt4DDGffv/TnhUh6kr+URt05394xdyHp6g4LMSJEExvMX8z8MBTYIupmlnmCRMCeg92FAIEBWaRaVYVitQqrSbm14B+/ucJVtKgEwTYnkPvocFVQMpbQr0yLgGY5+/4xE4X3n78M0sxBZiAbA7H764LQJss0MndXqVUamqmOhuZI6fX5YXUYPU5lgIuDEc7bzMYo2Rify6jChY5mxM7+fr0wuA+u2u+mQLAC8nyNx74wbAJmvl9kKOiESiwvIEjUNzFvLFhXCTKpqkDSwuLW+/sCGDui6YUsSb3AgiMXZwCzhQ1QgA2gjoPL76YO8IsbLb/NKet+0VdAEgMSREfTyuMC16heZAEg6rrfb12+HwWGWrBckEtYAfwjb5/p"}
Everything else gets saved except for the base64 column. Please assist.
The problem is the semicolon in data:image/png;base64, in combination with " double quotes.
The most easy would be to save the base64 string without that prefix, which breaks the syntax and then assume it is all PNG images (or add a further field, which indicates the encoding of each image).
This problem isn't specific to Room, but specific to Java with SQLite, because that semicolon terminates the statement (which Room will generate). In Java, one can use ' single-quotes only for the primitive data-type char, while the complex data-type String excepts " double-quotes. The only way to get around this limitation, is not trying to save a String containing a ;.
To provide an example of what I mean:
private String base64String = null;
private String base64Type = "png";
public String getBase64Image() {
if(this.base64String != null) {
return "data:image/" + this.base64Type + ";base64," + this.base64String;
} else {
return null;
}
}
I'm trying to send a request to get back an array of an object - Coupon when I submit the request I get the answer-
Direct self-reference leading to cycle (through reference chain:
java.util.HashSet[0] => model.Coupon["emptyCoupon"] => model.Coupon["emptyCoupon"])
The model.Coupon probably does the problem.
empty coupon is intended to be returned if the requested coupon does not exist.
public static final int NO_ID = -1;
private static final Coupon EMPTY_COUPON = new Coupon(NO_ID, null, null, null, NO_ID, NO_ID, null, NO_ID, null);
private long id = NO_ID;
private String title;
private LocalDate startDate;
private LocalDate endDate;
private int amount;
private int category;
private String message;
private double price;
private String image;
public Coupon() {
}
private Coupon(long id, String title, LocalDate start_date, LocalDate end_date, int amount, int category,
String message, double price, String image) {
this.id = id;
this.title = title;
this.startDate = start_date;
this.endDate = end_date;
this.amount = amount;
this.category = category;
this.message = message;
this.price = price;
this.image = image;
}
public Coupon getEmptyCoupon() {
return EMPTY_COUPON;
}
Before I added the EMPTY_COUPON I had no problems with the requests.
I want the emptyCoupon in the code, and I'll be happy to help
Since you are serializing to JSON or XML with Jersey, you may not have cycles in your object graph.
Jersey doesn't have a #JsonBackReference like Jackson does, so you might consider to move the EMPTY_COUPON in a separate class (something like Constants.java) and obtain it from there.
Other options are to add #XmlIgnore to your field or to switch to another JSON serializer like Jackson.
I am trying to add a database to my android app through the Room Persistence library and i am getting this error:
error: Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
Tried the following constructors but they failed to match:
User(int,java.lang.String,java.lang.String,int,int,int,java.lang.String) -> [param:id -> matched field:unmatched, param:name -> matched field:unmatched, param:gender -> matched field:unmatched, param:age -> matched field:unmatched, param:weight -> matched field:unmatched, param:height -> matched field:unmatched, param:workout -> matched field:unmatched]
Here is my code:
#Entity
public class User {
#PrimaryKey
private int userId;
private String userName;
private String userGender;
private int userAge;
private int userWeight;
private int userHeight;
private String workoutPlan;
public User(int id, String name, String gender, int age, int weight, int height, String workout) {
this.userId = id;
this.userName = name;
this.userGender = gender;
this.userAge = age;
this.userWeight = weight;
this.userHeight = height;
this.workoutPlan = workout;
} ...
Can someone please tell me what i am doing wrong or what i missed?
Please change names of the parameters such that it matches entity attributes.
public User(int userId, String userName, String userGender, int userAge, int userWeight, int userHeight, String workoutPlan) {
this.userId = userId;
this.userName = userName;
this.userGender = userGender;
this.userAge = userAge;
this.userWeight = userWeight;
this.userHeight = userHeight;
this.workoutPlan = workoutPlan;
} ...
For persistance, it uses JavaBeans conventions in Room. For more information:
https://developer.android.com/training/data-storage/room/defining-data#java
Kotlin :
#Entity(tableName = "t_article_tabs")
data class WxArticleTabsEntity(
#ColumnInfo(name = "tabId") #PrimaryKey #SerializedName("id") val id: Int?,
#ColumnInfo(name = "tabName") #SerializedName("name") val name: String?,
...
#Ignore #SerializedName("children") val children: List<Any>?,
)
Change to :
#Entity(tableName = "t_article_tabs")
data class WxArticleTabsEntity(
#ColumnInfo(name = "tabId") #PrimaryKey #SerializedName("id") val id: Int?,
#ColumnInfo(name = "tabName") #SerializedName("name") val name: String?,
...
){
#Ignore #SerializedName("children") val children: List<Any>? = null
}
you can also try this:-
#Ignore
public User(int userId, String userName, String userGender, int userAge, int
userWeight, int userHeight, String workoutPlan ) {
this.userId = userId;
this.userName = userName;
this.userGender = userGender;
this.userAge = userAge;
this.userWeight = userWeight;
this.userHeight = userHeight;
this.workoutPlan = workoutPlan;
}
public User(String userName, String userGender, int userAge, int
userWeight, int userHeight, String workoutPlan) {
this.userName = userName;
this.userGender = userGender;
this.userAge = userAge;
this.userWeight = userWeight;
this.userHeight = userHeight;
this.workoutPlan = workoutPlan;
}
I got around this same problem by just adding a empty constructor.
public User(){}
I also got this error. Only one of my attributes in my constructor did not match and I was finding it rather confusing. My variable (outside the constructor) was named mURL and I was trying to match it to url within the constructor.
Instead, I should have set the outer variable to mUrl. Yes, capitalising the last 2 letters gave me that error. Setting this.mUrl = url instead of this.mURL = url solved the error.
In my case, I solved problem just removing #Ignore from default constructor.
If you copied your code from some place, and have #Ignore in default constructor then need to remove #Ignore from default constructor.
Before:
#Ignore
public Card(){}
After:
public Card(){}
I just added because it's happen with me.
I am trying to create an application using springboot-java,
front end as html/css/javascript. I get the below error while doing a post to create an employee record. I am passing a join date which is causing the error.
failed - {"readyState":4,
"responseText":"{\"timestamp\":1515066928232,
\"status\":500,
\"error\":\"Internal Server Error\",
\"exception\":\"java.time.format.DateTimeParseException\",
\"message\":\"Text '01-17-2018' could not be parsed at index 0\",
\"path\":\"/employee/\"}",
"responseJSON":{"timestamp":1515066928232,
"status":500,
"error":"Internal Server Error",
"exception":"java.time.format.DateTimeParseException",
"message":"Text '01-17-2018' could not be parsed at index 0",
"path":"/employee/"},
"status":500,
"statusText":"error"}
Below is the code I use in java:
private static final long serialVersionUID = -7314008048174880868L;
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("MM-dd-yyyy");
private Integer organisation;
private String empName;
private String joinDate;
private String gender;
private String designation;
private String email;
public EmployeeDto(){
}
public EmployeeDto(Integer organisation, String empName, String joinDate, String gender,
String designation, String email) {
super();
this.organisation = organisation;
this.empName = empName;
this.joinDate = joinDate;
this.gender = gender;
this.designation = designation;
this.email = email;
}
public Employee buildEmployee(){
return new Employee(this.empName,LocalDate.parse(this.joinDate),this.gender,this.designation,this.email);
}
I use the below date converter:
#Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {
#Override
public Date convertToDatabaseColumn(LocalDate locDate) {
return (locDate == null ? null : Date.valueOf(locDate));
}
#Override
public LocalDate convertToEntityAttribute(Date sqlDate) {
return (sqlDate == null ? null : sqlDate.toLocalDate());
}
}
I am unable to find the root cause....
In buildEmployee() I think you want LocalDate.parse(this.joinDate, DATE_FORMAT) instead of LocalDate.parse(this.joinDate).
One often posted link here on Stack Overflow is How to debug small programs. In that blog post the first tip is to turn on compiler warnings and read them carefully. Putting your code into my Eclipse produces the following warning:
The value of the field EmployeeDto.DATE_FORMAT is not used
This may cause you to wonder why DATE_FORMAT is not used and why you wanted to have it there in the first place. Which in turn could inspire you to use it as intended, which fixes your error.
This is a problem iv encountered and tried most of the solutions that i have been offered so far and little seems to work , the problem making this harder to fix is for some reason the hibernate session wont print its details to the log providing me with very little in terms of error tracing. I want to upload a string of Json converted to a blob into the database . If anyone knows where i am going wrong or can provide and pointers this would be great as im struggling to solve this alone.
#Entity
#Table(name="workout")
public class Workout implements Serializable{
private static Logger logger = Logger.getLogger(Workout.class);
#Id
#Column(name="workout_id")
private int workout_id;
#Column(name="username")
private String username;
#Column(name="added_date")
private String added_date;
#Lob
#Column(name="workout")
Blob workout;
public int getWorkout_id() {
return workout_id;
}
public void setWorkout_id(int workout_id) {
this.workout_id = workout_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAdded_date() {
return added_date;
}
public void setAdded_date(String added_date) {
this.added_date = added_date;
}
public Blob getWorkout() {
return workout;
}
public void setWorkout(Blob workout) {
this.workout = workout;
}
}
method from Service that trys to upload
public String uploadWorkout(String json){
Workout w = new Workout();
w.setUsername("cmac458");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
w.setAdded_date(date.toGMTString());
w.setWorkout(getBLOBfromJSON(json));
w.setWorkout_id(4);
workoutDao.getSession().save(w);
return "done";
}
I am using the basic hibernatetemplate.save(entity) that works in other parts of my application.
Any help here is much appreciated.
Thanks
Chris
I use byte[] instead ob Blob type, and that works fine.
#Lob
#Column(nullable = false, length = 2097152)
private byte[] data;