How set #ServerTimestamp annotation in custom object classes - Firestore - java

I have a field in the Firestore database that is TimeStamp and is in this format: Quarta-feira, 11 de Outubro de 2017 às 10:24:54 GMT-03:00
It is defined as: map.put("timestamp", FieldValue.serverTimestamp());
According to Firestore instructions, you need to add a annotation, directly to the model class.
I have in my class the TimeStamp field in String. I tried using TimeStamp and it does not work
What is the best way to solve this problem?
Code Class Model:
public class Servicos {
private String nome_produto;
private String duracao;
private String valor;
private String valor_old;
private String categoria;
private String categoria_nome;
private String sub_categoria;
private String sub_categoria_nome;
private String descricao;
private String duracao_milis;
private String timestamp;
public Servicos() {
}
public Servicos(String nome_produto, String duracao, String valor, String valor_old,
String categoria, String categoria_nome, String sub_categoria, String sub_categoria_nome,
String descricao, String duracao_milis, String timestamp){
this.nome_produto = nome_produto;
this.duracao = duracao;
this.valor = valor;
this.valor_old = valor_old;
this.categoria = categoria;
this.categoria_nome = categoria_nome;
this.duracao_milis = duracao_milis;
this.sub_categoria = sub_categoria;
this.sub_categoria_nome = sub_categoria_nome;
this.descricao = descricao;
this.timestamp = timestamp;
}
public String getNome_produto() {
return nome_produto;
}
public void setNome_produto(String nome_produto) {
this.nome_produto = nome_produto;
}
public String getDuracao() {
return duracao;
}
public void setDuracao(String duracao) {
this.duracao = duracao;
}
public String getValor() {
return valor;
}
public void setValor(String valor) {
this.valor = valor;
}
public String getValor_old() {
return valor_old;
}
public void setValor_old(String valor_old) {
this.valor_old = valor_old;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public String getCategoria_nome() {
return categoria_nome;
}
public void setCategoria_nome(String categoria_nome) {
this.categoria_nome = categoria_nome;
}
public String getSub_categoria() {
return sub_categoria;
}
public void setSub_categoria(String sub_categoria) {
this.sub_categoria = sub_categoria;
}
public String getSub_categoria_nome() {
return sub_categoria_nome;
}
public void setSub_categoria_nome(String sub_categoria_nome) {
this.sub_categoria_nome = sub_categoria_nome;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getDuracao_milis() {
return duracao_milis;
}
public void setDuracao_milis(String duracao_milis) {
this.duracao_milis = duracao_milis;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
Ref Firestore Documentation: Link Firestore
// If you're using custom Java objects in Android, add an #ServerTimestamp
// annotation to a Date field for your custom object classes. This indicates
// that the Date field should be treated as a server timestamp by the object mapper.
DocumentReference docRef = db.collection("objects").document("some-id");
// Update the timestamp field with the value from the server
Map<String,Object> updates = new HashMap<>();
updates.put("timestamp", FieldValue.serverTimestamp());
docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
// ...
// ...

Here's an example of how to use ServerTimestamp with a custom Java class:
public class Rating {
private String userId;
private #ServerTimestamp Date timestamp;
public Rating() {}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}

Try this:
public class Klass {
private Date timestamp;
public Klass() {}
#ServerTimestamp
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}

Related

How to create Gson object for entity class which has timestamp value?

I have a payload string and want to change it to values of entity. The payload as below:
{"resultCode":"200","resultMessage":"Success","consent":[{"name":"A","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"1.0","updateDate":1600658621871},{"name":"B","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"2.0","updateDate":1874819158457},{"name":"C","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"3.0","updateDate":1358819159457}]}
And the entities:
public class ListConsentResponse {
private String resultCode;
private String resultMessage;
private List<ConsentDTO> consent;
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public List<ConsentDTO> getConsent() {
return consent;
}
public void setConsent(List<ConsentDTO> consent) {
this.consent = consent;
}
}
public class ConsentDTO {
private String name;
private String sourceSystem;
private String updateBy;
private String remark;
private String version;
private Timestamp updateDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceSystem() {
return sourceSystem;
}
public void setSourceSystem(String sourceSystem) {
this.sourceSystem = sourceSystem;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Timestamp getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Timestamp updateDate) {
this.updateDate = updateDate;
}
}
But when I parse to json using GsonBuilder :
ListConsentResponse listConsentResponse = Utility.createGsonObject()
.fromJson(payload, ListConsentResponse.class);
I have error:
com.google.gson.JsonSyntaxException: 1600658621871
Is there any way help me get parse the string with Timestamp value to entity. Or at least can I change the Timestamp value to String value in payload (For example change 1600658621871 to "1600658621871").
Thanks.

Springboot Jpa updating records instead of inserting

I'm doing the below query to find records that are in a temp table and dont exist in master then insert the results to the master table
#Query(value = "select b from InboundTemp b where b.transactionId NOT IN (SELECT p2.transactionId FROM Inbound p2)")
ArrayList<InboundTemp> findMissing();
However if I pass a single result object to the JpaRepository save method (To update the master table)it does an update instead of an insert.
what would I be doing wrong?
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(name="inbound_postpay_temp")
#NamedQuery(name="InboundPostpayTemp.findAll", query="SELECT i FROM InboundPostpayTemp i")
public class InboundPostpayTemp implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private int id;
#Column(name="bill_ref_no")
private String billRefNo;
#Column(name="business_shortcode")
private String businessShortcode;
private byte clicked;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="created_at")
private Date createdAt;
private String kpresponse;
private String KPtransaction_id;
#Column(name="mpesa_sender")
private String mpesaSender;
private String msisdn;
#Column(name="Network")
private String network;
#Column(name="org_account_balance")
private float orgAccountBalance;
private String status;
#Column(name="transaction_amount")
private float transactionAmount;
#Column(name="transaction_id")
private String transactionId;
#Column(name="transaction_time")
private String transactionTime;
#Column(name="transaction_type")
private String transactionType;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="updated_at")
private Date updatedAt;
public InboundPostpayTemp() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getBillRefNo() {
return this.billRefNo;
}
public void setBillRefNo(String billRefNo) {
this.billRefNo = billRefNo;
}
public String getBusinessShortcode() {
return this.businessShortcode;
}
public void setBusinessShortcode(String businessShortcode) {
this.businessShortcode = businessShortcode;
}
public byte getClicked() {
return this.clicked;
}
public void setClicked(byte clicked) {
this.clicked = clicked;
}
public Date getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getKpresponse() {
return this.kpresponse;
}
public void setKpresponse(String kpresponse) {
this.kpresponse = kpresponse;
}
public String getKPtransaction_id() {
return this.KPtransaction_id;
}
public void setKPtransaction_id(String KPtransaction_id) {
this.KPtransaction_id = KPtransaction_id;
}
public String getMpesaSender() {
return this.mpesaSender;
}
public void setMpesaSender(String mpesaSender) {
this.mpesaSender = mpesaSender;
}
public String getMsisdn() {
return this.msisdn;
}
public void setMsisdn(String msisdn) {
this.msisdn = msisdn;
}
public String getNetwork() {
return this.network;
}
public void setNetwork(String network) {
this.network = network;
}
public float getOrgAccountBalance() {
return this.orgAccountBalance;
}
public void setOrgAccountBalance(float orgAccountBalance) {
this.orgAccountBalance = orgAccountBalance;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public float getTransactionAmount() {
return this.transactionAmount;
}
public void setTransactionAmount(float transactionAmount) {
this.transactionAmount = transactionAmount;
}
public String getTransactionId() {
return this.transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getTransactionTime() {
return this.transactionTime;
}
public void setTransactionTime(String transactionTime) {
this.transactionTime = transactionTime;
}
public String getTransactionType() {
return this.transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public Date getUpdatedAt() {
return this.updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
The master class is the same
Below is the method that is persisting to dB
missing = temprepo.findMissing();
for (InboundPostpayTemp inboundPostpayTemp2 : missing) {
postpaytransaction.setBillRefNo(inboundPostpayTemp2.getBillRefNo());
postpaytransaction.setBusinessShortcode("");
// postpaytransaction.setClicked("0".t);
postpaytransaction
.setCreatedAt(new java.sql.Timestamp(inboundPostpayTemp2.getCreatedAt().getTime()));
postpaytransaction.setMpesaSender(inboundPostpayTemp2.getMpesaSender());
postpaytransaction.setMsisdn(inboundPostpayTemp2.getMsisdn());
postpaytransaction.setTransactionAmount(inboundPostpayTemp2.getTransactionAmount());
postpaytransaction.setTransactionId(inboundPostpayTemp2.getTransactionId());
postpaytransaction.setTransactionType("Paybill-Repost");
postpaytransaction.setStatus("CONFIRMED");
postpaytransaction.setTransactionTime(inboundPostpayTemp2.getTransactionTime());
//postpaytransactionx.add(postpaytransaction);
inboundpostpayrepo.save(postpaytransaction);
}
The only reason why JPA does an update instead of insert is that the Primary Key already exists in your persistence layer or your table. So kindly check or post your source code in order to review it and find what is wrong (if the issue is not in your data).
Now that you have updated the question with the source code, your bug is probably on the instantiation of the postpaytransaction object.
try to insert into your loop before everything else
postpaytransaction = new PostPayTransaction ()
I had the exactly same issue. My point was that the SpringBoot was automatically recreating the DB on startup, incorrectly creating the identity column in the table.
Look for spring.jpa.hibernate.ddl-auto.

Error in One to many mapping in hibernate-spring integration

I need to map two pojo class using one to many, but getting the below error
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'testCaseStepsform' at row 1
When I saw the table created by hibernate, I found that a column with data type blob is created
I am adding the code below.
#Entity
#Table(name="TEST_CASE_DESC")
public class TestCaseForm implements Serializable{
/**
*
*/
private static final long serialVersionUID = 10001234L;
#Id
#Column(name="TEST_CASE_ID")
private String testCaseId;
#Column(name="PROJECT_NAME")
private String projectName;
#Column(name="PROJECT_ID")
private String projectId;
#Column(name="RELEASE_NAME")
private String releaseName;
#Column(name="RELEASE_ID")
private String releaseId;
#Column(name="ITERATION")
private String iteration;
#Column(name="TITLE")
private String title;
#Column(name="CREATED_BY")
private String createdBy;
#Column(name="CREATION_DATE")
private Date creationDate;
#Column(name="DESCRIPTION")
private String description;
#Column(name="PRE_CONDITION")
private String preCondition;
#Column(name="POST_CONDITION")
private String postCondition;
#Column(name="TYPE")
private String type;
#Column(name="IMPORTANCE")
private String importance;
private ArrayList<TestCaseStepsForm> testCaseStepsform = new ArrayList<TestCaseStepsForm>();
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPreCondition() {
return preCondition;
}
public void setPreCondition(String preCondition) {
this.preCondition = preCondition;
}
public String getPostCondition() {
return postCondition;
}
public void setPostCondition(String postCondition) {
this.postCondition = postCondition;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getRelease() {
return releaseName;
}
public void setReleaseName(String releaseName) {
this.releaseName = releaseName;
}
public String getReleaseId() {
return releaseId;
}
public void setReleaseId(String releaseId) {
this.releaseId = releaseId;
}
public String getIteration() {
return iteration;
}
public void setIteration(String iteration) {
this.iteration = iteration;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getReleaseName() {
return releaseName;
}
public String getImportance() {
return importance;
}
public void setImportance(String importance) {
this.importance = importance;
}
#OneToMany(mappedBy = "TEST_CASE_DESC", cascade = CascadeType.ALL)
public ArrayList<TestCaseStepsForm> getTestCaseStepsform() {
return testCaseStepsform;
}
public void setTestCaseStepsform(ArrayList<TestCaseStepsForm> testCaseStepsform) {
this.testCaseStepsform = testCaseStepsform;
}
public String getTestCaseId() {
return testCaseId;
}
public void setTestCaseId(String testCaseId) {
this.testCaseId = testCaseId;
}
}
#Entity
#Table(name="TEST_CASE_STEP")
public class TestCaseStepsForm implements Serializable{
/**
*
*/
private static final long serialVersionUID = 123456788091L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="SERIAL_NUMBER")
private String serialNumber;
#Column(name="TEST_CASE_ID")
private String testCaseId;
#Column(name="INPUT")
private String input;
#Column(name="EXPCETED_OUTPUT")
private String expectedOutput;
#Column(name="STATUS")
private String status;
private TestCaseForm testCaseForm;
public String getTestCaseId() {
return testCaseId;
}
public void setTestCaseId(String testCaseId) {
this.testCaseId = testCaseId;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getExpectedOutput() {
return expectedOutput;
}
public void setExpectedOutput(String expectedOutput) {
this.expectedOutput = expectedOutput;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#ManyToOne( fetch = FetchType.LAZY)
#JoinColumn(name = "TEST_CASE_ID", nullable = false)
public TestCaseForm getTestCaseForm() {
return testCaseForm;
}
public void setTestCaseForm(TestCaseForm testCaseForm) {
this.testCaseForm = testCaseForm;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
}
#Configuration
public class TestCaseConfig {
#Bean(name="testCaseForm1")
public TestCaseForm testCaseForm1(){
TestCaseForm tst = new TestCaseForm();
tst.setTestCaseId("1122233");
tst.setProjectId("1234");
tst.setReleaseName("June");
tst.setReleaseId("1707");
tst.setIteration("2");
tst.setProjectName("ExpressPay");
tst.setTitle("ExpressPay");
tst.setCreatedBy("Anirban Deb");
tst.setCreationDate(new Date());
tst.setDescription("ExpressPay Login");
tst.setPreCondition("Active account");
tst.setPostCondition("success");
TestCaseStepsForm str1 = new TestCaseStepsForm();
str1.setTestCaseId("1122233");
str1.setInput("Hello World");
str1.setExpectedOutput("Bye Bye world");
str1.setStatus("Run");
str1.setTestCaseForm(tst);
TestCaseStepsForm str2 = new TestCaseStepsForm();
str2.setTestCaseId("1122233");
str2.setInput("Hello World");
str2.setExpectedOutput("Bye Bye world");
str2.setStatus("Run");
str1.setTestCaseForm(tst);
tst.getTestCaseStepsform().add(str1);
tst.getTestCaseStepsform().add(str2);
return tst;
}
}
public class Main {
public static void main(String[] args) throws MessagingException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("core-bean.xml");
TestCaseForm test1 = context.getBean("testCaseForm1",TestCaseForm.class);
ITestCaseService testCase = context.getBean("testCaseServiceImp", ITestCaseService.class);
testCase.inserTestCase(test1);
[enter image description here][1]
stopWatch.stop();
System.out.println("Time taken in execution : "+stopWatch.getTotalTimeSeconds());
}
}
You should choose to annotate object properties or getters. Don't use it simultaneously.
Apart, #xl0e answer
You need to correct mapping
#OneToMany(mappedBy = "testCaseForm", cascade = CascadeType.ALL)
public ArrayList<TestCaseStepsForm> getTestCaseStepsform() {
return testCaseStepsform;
}

Fetching all the array elements using rs.next()

I'm having a problem fetching data from database.
I'm trying to fetch the list of array.
But my problem is that i can only get the last element of the array maybe because it overwrites the previous one.
Here's my code.
String sql;
sql = "select * from NM_PROPERTIES_LOADER";
ResultSet rs = stmt.executeQuery(sql);
String prop_name = null;
String prop_value = null;
PropertyData reader = new PropertyData();
while(rs.next()){
prop_name = rs.getString("prop_name");
prop_value = rs.getString("prop_value");
reader.setPropName(prop_name);
reader.setPropValue(prop_value);
..//other setter..
System.out.println(prop_name + " " + prop_value);
}
prop.add(reader);
In my sysout I can retrieve all the datas. but on my page only the last element is retrieved. Here's my dao class.
public class PropertyData {
private int id;
private String propName;
private String propValue;
private String engineName;
private String desc;
private Date createdAt;
private String createdBy;
private Date updatedAt;
private String updatedBy;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPropName() {
return propName;
}
public void setPropName(String propName) {
this.propName = propName;
}
public String getPropValue() {
return propValue;
}
public void setPropValue(String propValue) {
this.propValue = propValue;
}
public String getEngineName() {
return engineName;
}
public void setEngineName(String engineName) {
this.engineName = engineName;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
In every iteration of the loop, you overwrite the content of reader.
You want to create reader inside the loop, not outside,
and also do prop.add(reader) inside the loop, not outside.
Like this:
String sql = "select * from NM_PROPERTIES_LOADER";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
PropertyData reader = new PropertyData();
String name = rs.getString("prop_name");
String value = rs.getString("prop_value");
reader.setPropName(name);
reader.setPropValue(value);
// other setter calls..
prop.add(reader);
}

How parcelable custom arraylist?

I have two classes which implement Parcelable. And objects of one of them I have to write to a list. First model:
public class Challenge implements Parcelable {
private long id;
#JsonProperty("max_volume")
private int maxVolume;
#JsonProperty("current_volume")
private int currentVolume;
private String name;
private String description;
#JsonProperty("max_count")
private int maxCount;
#JsonProperty("date_from")
private Date dateFrom;
#JsonProperty("date_to")
private Date dateTo;
#JsonProperty("create_time")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm ZZZZ")
private Date createTime;
private ChallengeStatus status;
#JsonProperty("update_date")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm ZZZZ")
private Date updateTime;
private ChallengeCategory category;
private Subject subject;
private ArrayList<User> userArrayList;
private int practice;
public double getProgress() {
return progress;
}
public void setProgress(double progress) {
this.progress = progress;
}
public int getPractice() {
return practice;
}
public void setPractice(int practice) {
this.practice = practice;
}
private double progress;
public Challenge() {
}
private Creator<User> creator;
protected Challenge(Parcel in) {
id = in.readLong();
maxVolume = in.readInt();
currentVolume = in.readInt();
name = in.readString();
description = in.readString();
maxCount = in.readInt();
// dateFrom = new Date(in.readLong());
// dateTo = new Date(in.readLong());
// createTime = new Date(in.readLong());
// status = ChallengeStatus.getEnum(in.readString());
// updateTime = new Date(in.readLong());
// category = ChallengeCategory.getEnum(in.readString());
subject = in.readParcelable(Subject.class.getClassLoader());
userArrayList = in.readTypedList(userArrayList, User.CREATOR);
}
public static final Creator<Challenge> CREATOR = new Creator<Challenge>() {
#Override
public Challenge createFromParcel(Parcel in) {
return new Challenge(in);
}
#Override
public Challenge[] newArray(int size) {
return new Challenge[size];
}
};
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getMaxVolume() {
return maxVolume;
}
public void setMaxVolume(int maxVolume) {
this.maxVolume = maxVolume;
}
public int getCurrentVolume() {
return currentVolume;
}
public void setCurrentVolume(int currentVolume) {
this.currentVolume = currentVolume;
}
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 int getMaxCount() {
return maxCount;
}
public void setMaxCount(int maxCount) {
this.maxCount = maxCount;
}
public Date getDateFrom() {
return dateFrom;
}
public void setDateFrom(Date dateFrom) {
this.dateFrom = dateFrom;
}
public Date getDateTo() {
return dateTo;
}
public void setDateTo(Date dateTo) {
this.dateTo = dateTo;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public ChallengeStatus getStatus() {
return status;
}
public void setStatus(ChallengeStatus status) {
this.status = status;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public ChallengeCategory getCategory() {
return category;
}
public void setCategory(ChallengeCategory category) {
this.category = category;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
#Override
public int describeContents() {
return 0;
}
public ArrayList<User> getUserArrayList() {
return userArrayList;
}
public void setUserArrayList(ArrayList<User> userArrayList) {
this.userArrayList = userArrayList;
}
public static Creator<Challenge> getCREATOR() {
return CREATOR;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeInt(maxVolume);
dest.writeInt(currentVolume);
dest.writeString(name);
dest.writeString(description);
dest.writeInt(maxCount);
// dest.writeLong(dateFrom.getTime());
// dest.writeLong(dateTo.getTime());
// dest.writeLong(createTime.getTime());
// dest.writeString(status.toString());
// dest.writeLong(updateTime.getTime());
// dest.writeString(category.toString());
dest.writeParcelable(subject, flags);
dest.writeTypedList(userArrayList);
}
}
And I have a problem at this line: userArrayList = in.readTypedList(userArrayList, User.CREATOR); It looks like this: And example of the second model:
public class User implements Parcelable {
long id;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm ZZZZ")
Date time;
String image_src;
String first_name;
String last_name;
public User() {
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getImage_src() {
return image_src;
}
public void setImage_src(String image_src) {
this.image_src = image_src;
}
protected User(Parcel parcel) {
id = parcel.readLong();
time = new Date(parcel.readLong());
image_src = parcel.readString();
first_name = parcel.readString();
last_name = parcel.readString();
}
public static final Creator<User> CREATOR = new Creator<User>() {
#Override
public User createFromParcel(Parcel in) {
return new User(in);
}
#Override
public User[] newArray(int size) {
return new User[size];
}
};
public static Creator<User> getCREATOR() {
return CREATOR;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(id);
// parcel.writeLong(time.getTime());
parcel.writeString(image_src);
parcel.writeString(first_name);
parcel.writeString(last_name);
}
}
Can you help me to find my mistake?
You must initialized userArrayList before use it:
userArrayList = new ArrayList<User>();
in.readTypedList(userArrayList, User.CREATOR);
Initialize ArraList and retrieve the data to this list from parcelable.
Something like this:
userArrayList = new ArrayList<User>();
in.readTypedList(userArrayList, User.CREATOR);

Categories