I need to save data into object
Here is my object class where I must store data:
public static class FilterEntity implements Serializable {
public int ageFrom;
public int ageTo;
public String sex;
public String status;
public void setAgeFrom()
{
this.ageFrom = ageFrom;
}
public void setAgeTo()
{
this.ageTo = ageTo;
}
public void setSex()
{
this.sex = sex;
}
public void setStatus()
{
this.status = status;
}
public Integer getAgeFrom()
{
return ageFrom;
}
public Integer getAgeTo()
{
return ageTo;
}
public String getSex()
{
return sex;
}
public String getStatus()
{
return status;
}
}
Is it correct implementation of serialization?
In the main activity I'm saving data to FilterEntity object
private FilterEntity filter = new FilterEntity();
filter.status = valueOf(spStatusForSearch.toString());
filter.sex = valueOf(rgSex);
filter.ageTo = sbAgeHigh.getProgress();
filter.ageFrom = sbAgeLow.getProgress();
Can I do it such way?
How I can get access to data, from the third class?
don't use static
public class FilterEntity implements Serializable {
public int ageFrom;
public int ageTo;
public String sex;
public String status;
public void setAgeFrom()
{
this.ageFrom = ageFrom;
}
public void setAgeTo()
{
this.ageTo = ageTo;
}
public void setSex()
{
this.sex = sex;
}
public void setStatus()
{
this.status = status;
}
public Integer getAgeFrom()
{
return ageFrom;
}
public Integer getAgeTo()
{
return ageTo;
}
public String getSex()
{
return sex;
}
public String getStatus()
{
return status;
}
}
To set Values to Model Class
FilterEntity filter = new FilterEntity();
filter.setStatus(spStatusForSearch.toString());
filter.setSex(rgSex);
filter.setAgeTo(sbAgeHigh.getProgress());
filter.setAgeFrom(sbAgeLow.getProgress());
And to get Values
String status = filter.getStatus();
String sex = filter.getSex();
String ageTo = filter.getAgeTo();
String ageFrom = filter.getAgeFrom();
public class FilterEntity
{
public int ageFrom;
public int ageTo;
public String sex;
public String status;
public FilterEntity(int ageFrom, int ageTo, String sex,String status)
{
this.ageFrom = ageFrom;
this.ageTo = ageTo;
this.sex = sex;
this.status = status;
}
public int getAgeFrom()
{
return ageFrom;
}
public int getAgeTo()
{
return ageTo;
}
public String getSex()
{
return sex;
}
public String getStatus()
{
return status;
}
}
// in your main activity file where your are saving the data
static ArrayList<FilterEntity> data=new ArrayList<FilterEntity>();
data.add(new FilterEntity(sbAgeLow.getProgress(),sbAgeHigh.getProgress(),valueOf(rgSex),valueOf(spStatusForSearch.toString())));
// you can add multiple like this
/*Now pass this arraylist to your third activity through intent or make this arraylist static so will be able to access this arraylist anywhere through the name of the class example: MainActivity.data*/
//Now in the third activity where you want the data of the object , get the arraylist
ArrayList data=MainActivity.data;
Iterator iterotor=data.iterator();
while (iterotor.hasNext())
{
FilterEntity filterEntity=iterotor.next();
// the multiple values you add
String status = filterEntity.getStatus();
String sex = filterEntity.getSex();
int ageTo = filterEntity.getAgeTo();
int ageFrom = filterEntity.getAgeFrom();
}
Related
I am trying to use json patch to update an object using PATCH in my app.
I want to update only 2 fields in my object and they might be null before updating.
Each time I try and update, the whole object gets updated.
How do I restrict this?
I've tried multiple ways.
#PatchMapping("/bmwsales/updateweb/{id}")
public ResponseEntity<?> updateVehicleTagWeb(#PathVariable(value="id") Integer id, #RequestBody Bmwsales v) throws JsonProcessingException{
ObjectMapper objMapper=new ObjectMapper();
JsonPatchBuilder jsonPatchBuilder=Json.createPatchBuilder();
JsonPatch jsonPatch=jsonPatchBuilder.replace("/templocation",v.getTemplocation()).replace("/rfidtag", v.getRfidtag()).build();
Bmwsales vehicle=bmwService.getVin(id).orElseThrow(ResourceNotFoundException::new);
BmwsalesUpdate veh=oMapper.asInput(vehicle);
BmwsalesUpdate vehPatched=patchHelp.patch(jsonPatch, veh, BmwsalesUpdate.class);
oMapper.update(vehicle, vehPatched);
System.out.println("the patched info is: "+vehicle.getRfidtag()+vehicle.getTemplocation());
bmwService.updateVehTag(vehicle);
return new ResponseEntity<>(HttpStatus.OK);
#Override
public void updateVehTag(Bmwsales vehicle) {
bmwsalesRepository.save(vehicle);
}
Jackson config:
#Configuration
public class JacksonConfig {
#Bean
public ObjectMapper objectMapper(){
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.findAndRegisterModules();
}}
Bmwsales class
#Entity(name="bmwsales")
#Table(name="bmwsales")
public class Bmwsales implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name="customerfirstname")
private String customerfirstname;
#Column(name="customerlastname")
private String customerlastname;
#Column(name="lastmileage")
private Integer lastmileage;
#Column(name="licensenum")
private String licensenum;
#Column(name="make")
private String make;
#Column(name="currentmileage")
private Integer currentmileage;
#Column(name="model")
private String model;
#Column(name="purchasedhere")
private String purchasedhere;
#JsonSerialize(using = JsonDateSerializer.class)
#Column(name="rfiddate")
private Timestamp rfiddate;
#Column(name="rfidtag")
private String rfidtag;
#Column(name="stocknum")
private String stocknum;
#Column(name="vehiclerole")
private String vehiclerole;
#NotBlank
#Column(name="vin")
private String vin;
#Column(name="year")
private Timestamp year;
#Column(name="vineight")
private String vineight;
#Column(name="taggingsource")
private String taggingsource;
#Column(name="vehicletype")
private String vehicletype;
#Column(name="salutation")
private String customersal;
#Column(name="customermiddlename")
private String customermiddlename;
#Column(name="suffix")
private String suffix;
#Column(name="address1")
private String address1;
#Column(name="address2")
private String address2;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="zip")
private String zip;
#Column(name="county")
private String county;
#Column(name="homephone")
private String homephone;
#Column(name="cellphone")
private String cellphone;
#Column(name="email")
private String email;
#Column(name="cobuyersalutation")
private String cobuyersal;
#Column(name="cobuyerfirstname")
private String cobuyerfirstname;
#Column(name="cobuyermiddlename")
private String cobuyermiddlename;
#Column(name="cobuyerlastname")
private String cobuyerlastname;
#Column(name="salesperson")
private String salesperson;
#Column(name="salesperson2")
private String salesperson2;
#Column(name="purchasedheredate")
private Timestamp purchasedheredate;
#Column(name="carwashmember")
private String carwashmember;
#Column(name="serviceadvisor")
private String serviceadvisor;
#JsonSerialize(using = JsonDateSerializer2.class)
#Column(name="openrodate")
private Date openrodate;
#Column(name="closerodate")
private Timestamp closerodate;
#Column(name="openro")
private String openro;
#Column(name="snstext")
private Timestamp snstext;
#Column(name="carwashexpire")
private Timestamp carwashexpire;
#Column(name="enterrodate")
private Timestamp enterrodate;
#Column(name="servicecarwash")
private String servicecarwash;
#Column(name="templocation")
private String templocation;
public Bmwsales(String vineight){
this.vineight=vineight;
}
public static class Builder{
private Integer id;
private String rfidtag;
//#JsonSerialize(using = JsonDateSerializer.class)
private Timestamp rfiddate;
private String vin;
private String vineight;
private String templocation;
public Builder setVin(String vin) {
this.vin=vin;
return this;
}
public Builder setVineight(String vineight) {
this.vineight=vineight;
return this;
}
public Builder setRfidtag(String rfidtag) {
this.rfidtag=rfidtag;
return this;
}
public Builder setRfiddate(Timestamp rfiddate) {
this.rfiddate=rfiddate;
return this;
}
public Builder setTemplocation(String templocation) {
this.templocation=templocation;
return this;
}
/*public Builder setOpenro(String openro){
this.openro=openro;
return this;
}
public Builder setOpenrodate(Date openrodate){
this.openrodate=openrodate;
return this;
}*/
public Bmwsales build(){
Bmwsales bmwsales=new Bmwsales(vin, vineight,rfidtag,rfiddate,
templocation);
return bmwsales;
}
}
public Bmwsales(String vin, String vineight, String rfidtag, Timestamp
rfiddate, String templocation){
this.vin=vin;
this.vineight=vineight;
this.rfiddate=rfiddate;
this.rfidtag=rfidtag;
this.templocation=templocation;
}
public Bmwsales(String customersal, String customerfirstname, String
customerlastname, String customermiddlename, String suffix,
String make, Integer currentmileage, String model, String
purchasedhere, String vehiclerole, String vin, String vineight,
Timestamp year, String taggingsource, String vehicletype,
String address1, String address2, String city, String state,
String zip, String county, String homephone, String cellphone,
String email, String cobuyersal, String cobuyerfirstname,
String cobuyermiddlename, String cobuyerlastname, String
salesperson, String salesperson2, Timestamp purchasedheredate,
String carwashmember, String serviceadvisor, Date openrodate,
Timestamp closerodate, Timestamp snstext, String openro,
Timestamp carwashexpire, Timestamp enterrodate, String
servicecarwash, Timestamp rfiddate, String rfidtag, String templocation){
super();
this.customersal=customersal;
this.customerfirstname=customerfirstname;
this.customermiddlename=customermiddlename;
this.customerlastname=customerlastname;
this.suffix=suffix;
this.make=make;
this.currentmileage=currentmileage;
this.model=model;
this.purchasedhere=purchasedhere;
this.vehiclerole=vehiclerole;
this.vin=vin;
this.vineight=vineight;
this.year=year;
this.taggingsource=taggingsource;
this.vehicletype=vehicletype;
this.address1=address1;
this.address2=address2;
this.city=city;
this.state=state;
this.zip=zip;
this.county=county;
this.homephone=homephone;
this.cellphone=cellphone;
this.email=email;
this.cobuyersal=cobuyersal;
this.cobuyerfirstname=cobuyerfirstname;
this.cobuyermiddlename=cobuyermiddlename;
this.cobuyerlastname=cobuyerlastname;
this.salesperson=salesperson;
this.salesperson2=salesperson2;
this.purchasedheredate=purchasedheredate;
this.carwashmember=carwashmember;
this.serviceadvisor=serviceadvisor;
this.openrodate=openrodate;
this.closerodate=closerodate;
this.snstext=snstext;
this.openro=openro;
this.carwashexpire=carwashexpire;
this.enterrodate=enterrodate;
this.servicecarwash=servicecarwash;
this.rfiddate=rfiddate;
this.rfidtag=rfidtag;
this.templocation=templocation;
};
public Bmwsales(){
}
public void setId(Integer id) {
this.id=id;
}
public Integer getId() {
return id;
}
public void setCustomersal(String customersal) {
this.customersal=customersal;
}
public String getCustomersal() {
return customersal;
}
public void setCustomerfirstname(String customerfirstname) {
this.customerfirstname=customerfirstname;
}
public String getCustomerfirstname() {
return customerfirstname;
}
public void setCustomermiddlename(String customermiddlename) {
this.customermiddlename=customermiddlename;
}
public String getCustomermiddlename() {
return customermiddlename;
}
public void setCustomerlastname(String customerlastname) {
this.customerlastname=customerlastname;
}
public String getCustomerlastname() {
return customerlastname;
}
public void setSuffix(String suffix) {
this.suffix=suffix;
}
public String getSuffix() {
return suffix;
}
public void setMake(String make) {
this.make=make;
}
public String getMake() {
return make;
}
public void setCurrentmileage(Integer currentmileage) {
this.currentmileage=currentmileage;
}
public Integer getCurrentmileage() {
return currentmileage;
}
public void setModel(String model) {
this.model=model;
}
public String getModel() {
return model;
}
public void setPurchasedhere(String purchasedhere) {
this.purchasedhere=purchasedhere;
}
public String getPurchasedhere() {
return purchasedhere;
}
public void setVehiclerole(String vehiclerole) {
this.vehiclerole=vehiclerole;
}
public String getVehiclerole() {
return vehiclerole;
}
public void setVin(String vin) {
this.vin=vin;
}
public String getVin() {
return vin;
}
public void setVineight(String vineight) {
this.vineight=vineight;
}
public String getVineight() {
return vineight;
}
public void setYear(Timestamp year) {
this.year=year;
}
public Timestamp getYear() {
return year;
}
public void setTaggingsource(String taggingsource) {
this.taggingsource=taggingsource;
}
public String getTaggingsource() {
return taggingsource;
}
public void setVehicletype(String vehicletype) {
this.vehicletype=vehicletype;
}
public String getVehicletype() {
return vehicletype;
}
public void setAddress1(String address1) {
this.address1=address1;
}
public String getAddress1() {
return address1;
}
public void setAddress2(String address2) {
this.address2=address2;
}
public String getAddress2() {
return address2;
}
public void setCity(String city) {
this.city=city;
}
public String getCity() {
return city;
}
public void setState(String state) {
this.state=state;
}
public String getState() {
return state;
}
public void setZip(String zip) {
this.zip=zip;
}
public String getZip() {
return zip;
}
public void setCounty(String county) {
this.county=county;
}
public String getCounty() {
return county;
}
public void setHomephone(String homephone) {
this.homephone=homephone;
}
public String getHomephone() {
return homephone;
}
public void setCellphone(String cellphone) {
this.cellphone=cellphone;
}
public String getCellphone() {
return cellphone;
}
public void setEmail(String email) {
this.email=email;
}
public String getEmail() {
return email;
}
public void setCobuyersal(String cobuyersal) {
this.cobuyersal=cobuyersal;
}
public String getCobuyersal() {
return cobuyersal;
}
public void setCobuyerfirstname(String cobuyerfirstname) {
this.cobuyerfirstname=cobuyerfirstname;
}
public String getCobuyerfirstname() {
return cobuyerfirstname;
}
public void setCobuyermiddlename(String cobuyermiddlename) {
this.cobuyermiddlename=cobuyermiddlename;
}
public String getCobuyermiddlename() {
return cobuyermiddlename;
}
public void setCobuyerlastname(String cobuyerlastname) {
this.cobuyerlastname=cobuyerlastname;
}
public String getCobuyerlastname() {
return cobuyerlastname;
}
public void setSalesperson(String salesperson) {
this.salesperson=salesperson;
}
public String getSalesperson() {
return salesperson;
}
public void setSalesperson2(String salesperson2) {
this.salesperson2=salesperson2;
}
public String getSalesperson2() {
return salesperson2;
}
public void setPurchasedheredate(Timestamp purchasedheredate) {
this.purchasedheredate=purchasedheredate;
}
public Timestamp getPurchasedheredate() {
return purchasedheredate;
}
public void setCarwashmember(String carwashmember) {
this.carwashmember=carwashmember;
}
public String getCarwashmember() {
return carwashmember;
}
public void setServiceadvisor(String serviceadvisor) {
this.serviceadvisor=serviceadvisor;
}
public String getServiceadvisor() {
return serviceadvisor;
}
public void setOpenrodate(Date openrodate) {
this.openrodate=openrodate;
}
public Date getOpenrodate() {
return openrodate;
}
public void setCloserodate(Timestamp closerodate) {
this.closerodate=closerodate;
}
public Timestamp getCloserodate() {
return closerodate;
}
public void setSnstext(Timestamp snstext) {
this.snstext=snstext;
}
public Timestamp getSnstext() {
return snstext;
}
public void setOpenro(String openro) {
this.openro=openro;
}
public String getOpenro() {
return openro;
}
public void setCarwashexpire(Timestamp carwashexpire) {
this.carwashexpire=carwashexpire;
}
public Timestamp getCarwashexpire() {
return carwashexpire;
}
public void setEnterrodate(Timestamp enterrodate) {
this.enterrodate=enterrodate;
}
public Timestamp getEnterrodate() {
return enterrodate;
}
public void setServicecarwash(String servicecarwash) {
this.servicecarwash=servicecarwash;
}
public String getServicecarwash() {
return servicecarwash;
}
public void setRfiddate(Timestamp rfiddate) {
this.rfiddate=rfiddate;
}
public Timestamp getRfiddate() {
return rfiddate;
}
public void setRfidtag(String rfidtag) {
this.rfidtag=rfidtag;
}
public String getRfidtag() {
return rfidtag;
}
public void setTemplocation(String templocation) {
this.templocation=templocation;
}
public String getTemplocation() {
return templocation;
}
public static Object Builder() {
return new Bmwsales.Builder();
}
}
How do I update only these fields?
Your code is long one why are you code getters/setters/constructors from typing.it will get a long time to develop.
Then what you must add this dependency into your POM.xml file
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
And adding this dependency you can generate your getters/setters and constructors from giving simple annotations like this.do not type those in your fingers.:-)
Then your code will be more easy to readable.
#Data //this will create all getters,setters,toString
#NoArgsConstructor //this will create default constructor
#AllArgsConstructor //this will create all argivements constructor
#Entity(name="bmwsales") //name means table name
public class Bmwsales implements Serializable{
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
// like this do all your columns
#NotNull(message="customer First Name is compulsory")
#Column(name="customerfirstname")
private String customerfirstname;
//your entity mapping here etc.
}
After that, if the user does not fill the required fields that message will trigger.
And your controller class that means your endpoint calling place should use #Valid annotation to your Entity class or DTO class(you do not get DTO).
#PatchMapping("/bmwsales/updateweb/{id}")
public ResponseEntity<String> updateVehicleTagWeb(#PathVariable(value="id") Integer id, #Valid #RequestBody Bmwsales v) throws JsonProcessingException{
ObjectMapper objMapper=new ObjectMapper();
JsonPatchBuilder jsonPatchBuilder=Json.createPatchBuilder();
JsonPatch jsonPatch=jsonPatchBuilder.replace("/templocation",v.getTemplocation()).replace("/rfidtag", v.getRfidtag()).build();
Bmwsales vehicle=bmwService.getVin(id).orElseThrow(ResourceNotFoundException::new);
BmwsalesUpdate veh=oMapper.asInput(vehicle);
BmwsalesUpdate vehPatched=patchHelp.patch(jsonPatch, veh, BmwsalesUpdate.class);
oMapper.update(vehicle, vehPatched);
System.out.println("the patched info is: "+vehicle.getRfidtag()+vehicle.getTemplocation());
bmwService.updateVehTag(vehicle);
return ResponseEntity.ok("Input is valid");
For more understanding what I said to refer to this link:-
https://www.baeldung.com/spring-boot-bean-validation
I'm using ParseSDK for android project. But I have a problem to access List of ParseObjects from another ParseObject class. I tried a lot of things, but anything didn't help me. Below I put my code.
Team team;
List<User> members = team.getMembers();
for(User user : members) {
user.getName();
}
#ParseClassName("Team")
public class Team extends ParseObject {
public static class Constant {
private static final String CREATED_BY = "createdBy";
private static final String NAME = "name";
public static final String CODE = "code";
private static final String PARTICIPANTS = "participants";
public static final String IS_ACTIVE = "isActive";
}
private String name;
private String code;
private User createdBy;
private List<User> members;
private int isActive;
public String getName() {
return getString(Constant.NAME);
}
public void setName(String name) {
this.name = name;
put(Constant.NAME, name);
}
public String getCode() {
return getString(Constant.CODE);
}
public void setCode(String code) {
this.code = code;
put(Constant.CODE, code);
}
public User getCreatedBy() {
return (User) getParseUser(Constant.CREATED_BY);
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
put(Constant.CREATED_BY, createdBy);
}
public List<User> getMembers() {
return getList(Constant.PARTICIPANTS);
}
public void setMembers(List<User> members) {
this.members = members;
put(Constant.PARTICIPANTS, members);
}
public int getIsActive() {
return getInt(Constant.IS_ACTIVE);
}
public void setIsActive(int isActive) {
this.isActive = isActive;
put(Constant.IS_ACTIVE, isActive);
}
#ParseClassName("_User")
public class User extends ParseUser {
private static class Constant {
private static final String NAME = "name";
private static final String GENDER = "gender";
private static final String BIRTHDATE = "birthdate";
private static final String FACEBOOK_ID = "facebookId";
private static final String AVATAR = "avatar";
private static final String WEIGHT = "weight";
private static final String WEIGHT_UNIT = "weightUnit";
private static final String EXPERIENCE_LEVEL = "experienceLevel";
private static final String GOALS = "goals";
private static final String SCORE = "score";
private static final String IS_PREMIUM = "isPremium";
private static final String IS_TRIAL_PERIOD = "isTrialPeriod";
private static final String TOTAL_WORKOUT_BUILDS = "totalWorkoutBuilds";
}
private String name;
private String gender;
private String facebookId;
private Date birthday;
private ParseFile avatar;
private int weight;
private String weighUnit;
private String experienceLevel;
private List<Goal> goals;
private int score;
private int isPremium;
private int isTrialPeriod;
private int totalWorkoutBuilds;
private String emailAddress;
public User() {
super();
}
public String getName() {
return validateStringResult(Constant.NAME);
}
public void setName(String name) {
put(Constant.NAME, name);
}
public String getGender() {
return validateStringResult(Constant.GENDER);
}
public void setGender(String gender) {
put(Constant.GENDER, gender);
}
public Date getBirthday() {
return getDate(Constant.BIRTHDATE);
}
public void setBirthday(Date birthday) {
put(Constant.BIRTHDATE, birthday);
}
public String getFacebookId() {
return validateStringResult(Constant.FACEBOOK_ID);
}
public void setFacebookId(String facebookId) {
put(Constant.FACEBOOK_ID, facebookId);
}
public ParseFile getAvatar() {
return getParseFile(Constant.AVATAR);
}
public void setAvatar(ParseFile avatar) {
put(Constant.AVATAR, avatar);
}
public int getWeight() {
return getInt(Constant.WEIGHT);
}
public void setWeight(int weight) {
put(Constant.WEIGHT, weight);
}
public String getWeightUnit() {
return validateStringResult(Constant.WEIGHT_UNIT);
}
public void setWeightUnit(String weightUnit) {
put(Constant.WEIGHT_UNIT, weightUnit);
}
public ExperienceLevel getExperienceLevel() {
final String result = validateStringResult(Constant.EXPERIENCE_LEVEL);
if (result.equalsIgnoreCase("intermediate")) {
return ExperienceLevel.INTERMEDIATE;
} else if (result.equalsIgnoreCase("advanced")) {
return ExperienceLevel.ADVANCED;
} else {
return ExperienceLevel.BEGINNER;
}
}
public void setExperienceLevel(String experienceLevel) {
put(Constant.EXPERIENCE_LEVEL, experienceLevel);
}
public List<Goal> getGoals() {
return getList(Constant.GOALS);
}
public void setGoals(List<Goal> goals) {
put(Constant.GOALS, goals);
}
public int getScore() {
return getInt(Constant.SCORE);
}
public void setScore(int score) {
put(Constant.SCORE, score);
}
public boolean isPremium() {
return getBoolean(Constant.IS_PREMIUM);
}
public void setPremium(boolean premium) {
put(Constant.IS_PREMIUM, premium);
}
public boolean isTrialPeriod() {
return getBoolean(Constant.IS_TRIAL_PERIOD);
}
public void setTrialPeriod(boolean trialPeriod) {
put(Constant.IS_TRIAL_PERIOD, trialPeriod);
}
public int getTotalWorkoutBuilds() {
return getInt(Constant.TOTAL_WORKOUT_BUILDS);
}
public void setTotalWorkoutBuilds(int totalWorkoutBuilds) {
put(Constant.TOTAL_WORKOUT_BUILDS, totalWorkoutBuilds);
}
private String validateStringResult(String key) {
final String result = getString(key);
return result == null ? "" : result;
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.kineticoach.traveltrainer, PID: 22022
java.lang.IllegalStateException: ParseObject has no data for 'name'. Call fetchIfNeeded() to get the data.
at com.parse.ParseObject.checkGetAccess(ParseObject.java:3607)
at com.parse.ParseObject.getString(ParseObject.java:3186)
at com.kineticoach.traveltrainer.models.objects.User.getName(User.java:25)
at com.kineticoach.traveltrainer.fragments.ProfileFragment.lambda$loadUserData$1$ProfileFragment(ProfileFragment.java:153)
at com.kineticoach.traveltrainer.fragments.-$$Lambda$ProfileFragment$Sdpefi97hyh_jTMOE2pWx3FVbo8.run(Unknown Source:2)
at android.os.Handler.handleCallback(Handler.java:874)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Follow this reference
we do not send the nested ParseObject's full data to cloud code. In order to get the data of the nested ParseObject, you have to do a query or fetch. The result you get from cloud code is pretty similar to the result you get from ParseQuery. We represent nested ParseObject as pointer and you have to fetch or query it in order to use it.
This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 5 years ago.
I have status like "In consultation","Waiting in Queue". all the data coming from json API and add all that data into array list using Pojo class.then how to sort this array list by Consultation status.
Patient Class:
public class Patient_Get_Set implements Serializable {
private String fullName;
private String age;
private String waitTime;
private String sex;
private String patientID;
private String gender;
private String dateOfBirth;
private String phoneNo;
private String Diagnosis;
private String Email;
private String token_id;
private String priority;
private String consultation_status;
private String case_number;
public String getCase_number() {
return case_number;
}
public void setCase_number(String case_number) {
this.case_number = case_number;
}
public String getConsultation_status() {
return consultation_status;
}
public void setConsultation_status(String consultation_status) {
this.consultation_status = consultation_status;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getToken_id() {
return token_id;
}
public void setToken_id(String token_id) {
this.token_id = token_id;
}
public String getConsultationstatus() {
return consultationstatus;
}
public void setConsultationstatus(String consultationstatus) {
this.consultationstatus = consultationstatus;
}
private String consultationstatus;
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getVisitorType() {
return visitorType;
}
public void setVisitorType(String visitorType) {
this.visitorType = visitorType;
}
private String visitorType;
public String getDiagnosis() {
return Diagnosis;
}
public void setDiagnosis(String diagnosis) {
Diagnosis = diagnosis;
}
private String patientJsonArray;
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setAge(String age) {
this.age = age;
}
public void setWaitTime(String waitTime) {
this.waitTime = waitTime;
}
public String getFullName() {
return fullName;
}
public String getAge() {
return age;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSex() {
return sex;
}
public String getWaitTime() {
return waitTime;
}
public void setPatientID(String patientID) {
this.patientID = patientID;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getPhoneNo() {
return phoneNo;
}
public String getPatientID() {
return patientID;
}
public void setPatientJsonArray(String patientJsonArray) {
this.patientJsonArray = patientJsonArray;
}
public String getPatientJsonArray() {
return patientJsonArray;
}
public String getGender() {
return gender;
}
}
Here is code what you can use for your custom need -
Collections.sort(list, new Comparator<Patient_Get_Set>() {
#Override
public int compare(final Patient_Get_Set object1, final Patient_Get_Set object2) {
List<String> statusList = new ArrayList();
statusList.add("consultation");statusList.add("queue"); statusList.add("waiting");
return new Integer(statusList.indexOf(object1.getConsultation_status())).compareTo(new Integer(statusList.indexOf(object2.getConsultation_status())));
}
});
add elements in statusList in same order in which order you want pojo class to be sorted.
You can use Collections to sort your array list objects.
for example your list as below.
ArrayList<Patient> list = new ArrayList<Patient>();
Then you can sort list using below code.
Collections.sort(list, new Comparator<Patient>() {
#Override
public int compare(final Patient object1, final Patient object2) {
return object1.getConsultation_status().compareTo(object2.getConsultation_status());
}
});
OR
If you are using Java version 1.8 then you can sort list using below code.
list.stream()
.sorted((object1, object2) -> object1.getConsultation_status().compareTo(object2.getConsultation_status()));
import static java.util.Comparator.comparing;
Collections.sort(list, comparing(MyObject::getStartDate));
compare data with comparing in java8 follow http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html
I have make a class which has a custom class object/variable and i want to make this class parcelable for passing it in to the intend so that i receive the reponse in next activity
MORE DETAILED
I Have class first ie
public class Data implements Parcelable{
#SerializedName("barlist")
Bar bar_list[];
public Bar[] getBarLst() {
return bar_list;
}
public void setBarLst(Bar lst[]) {
this.bar_list = lst;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeParcelableArray(bar_list, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
}
public static final Parcelable.Creator<Data> CREATOR = new Creator<Data>() {
public Data createFromParcel(Parcel source) {
Data data = new Data();
data.bar_list = (Bar[]) source.readParcelableArray(this.getClass().getClassLoader());
return data;
}
#Override
public Data[] newArray(int size) {
// TODO Auto-generated method stub
return new Data[size];
}
};
}
In the above class i have a custom type object/variable ie of type Bar
and my next class is ::
public class Bar implements Parcelable{
#SerializedName("name")
String Name;
#SerializedName("sex")
String sex;
#SerializedName("type")
String type;
#SerializedName("userid")
String userId;
#SerializedName("contactno")
String ContactNo;
#SerializedName("zipcode")
String zipCode;
#SerializedName("address")
String Address;
#SerializedName("email")
String Email;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getContactNo() {
return ContactNo;
}
public void setContactNo(String contactNo) {
ContactNo = contactNo;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(Name);
parcel.writeString(sex);
parcel.writeString(type);
parcel.writeString(userId);
parcel.writeString(ContactNo);
parcel.writeString(zipCode);
parcel.writeString(Address);
parcel.writeString(Email);
}
public static final Parcelable.Creator<Bar> CREATOR = new Creator<Bar>() {
public Bar createFromParcel(Parcel source) {
Bar barlst = new Bar();
barlst.Name = source.readString();
barlst.sex = source.readString();
barlst.ContactNo = source.readString();
barlst.type = source.readString();
barlst.userId = source.readString();
barlst.zipCode = source.readString();
barlst.Address = source.readString();
barlst.Email = source.readString();
return barlst;
}
#Override
public Bar[] newArray(int size) {
// TODO Auto-generated method stub
return new Bar[size];
}
};
}
I want to make a data class (first class) object be parcelable so in my first activity i did some this like this
EmptyRequest empt = new EmptyRequest();
Data responsestr = userManager.getMainMenuItems(empt,"url","Post","getBarList");
Intent myintent = new Intent(MainMenuPageActivity.this, BarListPageActivity.class);
Bundle mbundle = new Bundle();
mbundle.putParcelable("BARLIST", responsestr);
myintent.putExtras(mbundle);
startActivity(myintent);
till here my code worked fine and i kept the responsestr of type data into the parcelable
and in my next acitivity i tried to fetch data object like this
Data responseStr = (Response)getIntent().getParcelableExtra("BARLIST");
to fetch the object of type data but this didnt work and give exception the second activity class not found but my debugger reaches in the second activity.
Thanks in advance....
use
getIntent().getExtras().getParcelableExtra("BARLIST");
I'm trying to figure out a way to transform this JSON String into a Java object graph but I'm unable to do so. Below, I've inserted my JSON String, and my two classes. I've verified that its a valid json structure. I've been trying googles api (http://sites.google.com/site/gson/gson-user-guide) but it doesn't map the nested Photo Collection. Any ideas or alternate libraries?
{"photos":{"page":1,"pages":73514,"perpage":50,"total":"3675674","photo":[{"id":"5516612975","owner":"23723942#N07","secret":"b8fb1fda57","server":"5213","farm":6,"title":"P3100006.JPG","ispublic":1,"isfriend":0,"isfamily":0},{"id":"5516449299","owner":"81031835#N00","secret":"67b56722da","server":"5171","farm":6,"title":"Kaiser Boys Volleyball","ispublic":1,"isfriend":0,"isfamily":0}]},"stat":"ok"}
Photos.java
public class Photos {
private int pages;
private int perpage;
private String total;
private List<Photo> photo;
private String stat;
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getPerpage() {
return perpage;
}
public void setPerpage(int perpage) {
this.perpage = perpage;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public List<Photo> getPhoto() {
return photo;
}
public void setPhoto(List<Photo> photo) {
this.photo = photo;
}
public String getStat() {
return stat;
}
public void setStat(String stat) {
this.stat = stat;
}
}
Photo.java:
public class Photo {
private String id;
private String owner;
private String secret;
private String server;
private String farm;
private String title;
private int isPublic;
private int isFriend;
private int isFamily;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getFarm() {
return farm;
}
public void setFarm(String farm) {
this.farm = farm;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getIsPublic() {
return isPublic;
}
public void setIsPublic(int isPublic) {
this.isPublic = isPublic;
}
public int getIsFriend() {
return isFriend;
}
public void setIsFriend(int isFriend) {
this.isFriend = isFriend;
}
public int getIsFamily() {
return isFamily;
}
public void setIsFamily(int isFamily) {
this.isFamily = isFamily;
}
}
Use Jackson. It'll take care of converting to and from JSON. It provides multiple ways of approaching conversion, and is well-integrated with frameworks like Spring. Definitely one to know.