Android Parcelable JsonArray in Side JsonObject - java

When i am trying Parce this json data with GSON. I am unable to get JsonArray in side of JsonObject. Below is my code, every suggestion will get appriciated.
JSON DATA FROM SERVER :
{
"GetJobDetails": {
"MaxAmount": 0,
"CreatorId": 1,
"JobImages": [
{
"ImagePath": "http://192.168.1.108:8088/Uploads/6e660c0c-4a2b- 42dc-ad97-82cc3efe87a0.jpg",
"JobImageId": 1
},
{
"ImagePath": "http://192.168.1.108:8088/Uploads/ccf1087d-9f7e-4c21-bc61-8aa3fd924e05.jpg",
"JobImageId": 2
},
{
"ImagePath": "http://192.168.1.108:8088/Uploads/4333e8b6-0079-457f-a225-fd7900ea81b1.jpg",
"JobImageId": 3
}
],
}
}
In ACTIVITY :
Gson gson = new Gson();
String response = new String(mresponce);
JobDetails jobDetails= gson.fromJson(response, JobDetails .class);
Log.e("JobDetails ",""+jobDetails.getJobImagesList());
this log prints allways null even when i have images list there in my data.
MODEL CLASS :
public class JobDetails implements Parcelable {
private int MaxAmount;
private int CreatorId;
private List<JobImage> JobImages;
public JobDetails() {
}
public JobDetails(Parcel parcel) {
this.MaxAmount = parcel.readInt();
this.CreatorId= parcel.readInt();
this.JobImages = new ArrayList<JobImage>();
parcel.readTypedList(JobImages, JobImage.CREATOR);
}
// Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.MaxAmount);
dest.writeInt(this.CreatorId);
dest.writeList(this.JobImages);
// TODO: Not Parceling AddressList
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public JobDetails createFromParcel(Parcel in) {
return new JobDetails(in);
}
public JobDetails[] newArray(int size) {
return new JobDetails[size];
}
};
public List<JobImage> getJobImagesList() {
return JobImages;
}
public void setJobImagesList(List<JobImage> jobImages) {
JobImages = jobImages;
}
public int getMaxAmount() {
return MaxAmount;
}
public void setMaxAmount(int maxAmount) {
MaxAmount= maxAmount;
}
}
ANOTHER MODEL CLASS FOR JOBIMAGE:
public class JobImage implements Parcelable {
private String ImagePath;
private int JobImageId;
JobImage(){
}
public JobImage(Parcel in) {
this.ImagePath = in.readString();
this.JobImageId = in.readInt();
}
// Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.ImagePath);
dest.writeInt(this.JobImageId);
// TODO: Not Parceling AddressList
}
public static final Creator CREATOR = new Creator() {
public JobImage createFromParcel(Parcel in) {
return new JobImage(in);
}
public JobImage[] newArray(int size) {
return new JobImage[size];
}
};
public String getImagePath() {
return ImagePath;
}
public void setImagePath(String imagePath) {
ImagePath = imagePath;
}
public int getJobImageId() {
return JobImageId;
}
public void setJobImageId(int jobImageId) {
JobImageId = jobImageId;
}
}
Please help me to find what i am doing wrong in this :

Your top-level JSON object is not a JobDetails object, it is an object that has JobDetails member name GetJobDetails. You need to handle this level of your JSON. You can do it with a custom TypeAdapter, or perhaps easier, just make a container object and deserialize it.
class JobDetailContainer {
private JobDetails GetJobDetails;
public JobDetails getJobDetails() {
return GetJobDetails;
}
}
then use --
Gson gson = new Gson();
String response = new String(mresponce);
GetJobDetails getJobDetails= gson.fromJson(response, GetJobDetails.class);
Log.e("JobDetails ",""+getJobDetails.getJobDetails().getJobImagesList());

Agreed with #iagreen ...I should handel top level json object too..this is what i have done after doing some R&D
public class GetJobDetails {
public GetJobDetailsResult getGetJobDetailsResult() {
return GetJobDetailsResult;
}
public void setGetJobDetailsResult(GetJobDetailsResult GetJobDetailsResult) {
this.GetJobDetailsResult = GetJobDetailsResult;
}
}
For Inner Json :
public class GetJobDetailsResult {
private Integer MaxAmount;
private Integer CreatorTotJobPosted;
private List<JobImage> JobImages = new ArrayList<JobImage>();
public Integer getMaxAmount() {
return MaxAmount;
}
public void setMaxAmount(Integer MaxAmount) {
this.MaxAmount = MaxAmount;
}
public Integer getCreatorTotJobPosted() {
return CreatorTotJobPosted;
}
public void setCreatorTotJobPosted(Integer CreatorTotJobPosted) {
this.CreatorTotJobPosted = CreatorTotJobPosted;
}
public List<JobImage> getJobImages() {
return JobImages;
}
public void setJobImages(List<JobImage> JobImages) {
this.JobImages = JobImages;
}
}
Finally For To Hold JobImages
public class JobImage {
private String ImagePath;
private Integer JobImageId;
public String getImagePath() {
return ImagePath;
}
public void setImagePath(String ImagePath) {
this.ImagePath = ImagePath;
}
public Integer getJobImageId() {
return JobImageId;
}
public void setJobImageId(Integer JobImageId) {
this.JobImageId = JobImageId;
}
}
Final Step :
Gson gson = new Gson();
String response = new String(jsonObjectresponce.toString());
GetJobDetails getJobDetails = gson.fromJson(response, GetJobDetails.class);
GetJobDetailsResult result = getJobDetails.getGetJobDetailsResult();
// now result object contains my json data.

Related

Convert json string response to pojo

I am calling an API using rest template like below:
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
And here is the json response string that i receive from the API
{
"data": {
"individuals": [
{
"cust_xref_id": "abf",
"cust_frd_alrt_in": "n",
"cust_satis_trd_ct": "4",
"gam_open_rv_trd_ct": "4",
"cust_extnl_delinq_90_day_ct": "1",
"cust_extnl_delinq_in": "y"
}
]
}
}
how can i map this response into a pojo? please help.
Required classes for the conversion are below,
1. DataDTO
public class DataDTO {
private IndividualList data;
public IndividualList getData() {
return data;
}
public void setData(IndividualList data) {
this.data = data;
}}
2. IndividualList
public class IndividualList {
private List<IndividualDTO> individuals;
public List<IndividualDTO> getIndividuals() {
return individuals;
}
public void setIndividuals(List<IndividualDTO> individuals) {
this.individuals = individuals;
}}
3. IndividualDTO
public class IndividualDTO {
#JsonProperty("cust_xref_id")
private String custXrefId;
#JsonProperty("cust_frd_alrt_in")
private String custFrdAlrtIn;
#JsonProperty("cust_satis_trd_ct")
private String custSatisTrdCt;
#JsonProperty("gam_open_rv_trd_ct")
private String gamOpenRvTrdCt;
#JsonProperty("cust_extnl_delinq_90_day_ct")
private String custExtnlDelinq90DayCt;
#JsonProperty("cust_extnl_delinq_in")
private String custExtnlDelinqIn;
public String getCustXrefId() {
return custXrefId;
}
public void setCustXrefId(String custXrefId) {
this.custXrefId = custXrefId;
}
public String getCustFrdAlrtIn() {
return custFrdAlrtIn;
}
public void setCustFrdAlrtIn(String custFrdAlrtIn) {
this.custFrdAlrtIn = custFrdAlrtIn;
}
public String getCustSatisTrdCt() {
return custSatisTrdCt;
}
public void setCustSatisTrdCt(String custSatisTrdCt) {
this.custSatisTrdCt = custSatisTrdCt;
}
public String getGamOpenRvTrdCt() {
return gamOpenRvTrdCt;
}
public void setGamOpenRvTrdCt(String gamOpenRvTrdCt) {
this.gamOpenRvTrdCt = gamOpenRvTrdCt;
}
public String getCustExtnlDelinq90DayCt() {
return custExtnlDelinq90DayCt;
}
public void setCustExtnlDelinq90DayCt(String custExtnlDelinq90DayCt) {
this.custExtnlDelinq90DayCt = custExtnlDelinq90DayCt;
}
public String getCustExtnlDelinqIn() {
return custExtnlDelinqIn;
}
public void setCustExtnlDelinqIn(String custExtnlDelinqIn) {
this.custExtnlDelinqIn = custExtnlDelinqIn;
}}
Tested Response:
{"data":{"individuals":[{"cust_xref_id":"abf","cust_frd_alrt_in":"n","cust_satis_trd_ct":"4","gam_open_rv_trd_ct":"4","cust_extnl_delinq_90_day_ct":"1","cust_extnl_delinq_in":"y"}]}}

How to implelement this on retrofit?

Hello I am an android developer and i have never before faced this problem before "Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $" i am suspecting the issue is in my model.
this is the postman response as is
{
"Status": 200,
"Message": "OK",
"Data": {
"ServiceTypes": [
{
"Id": 1,
"ServiceTypeNameAr": "صيانة",
"ServiceTypeNameEn": "Maintenance",
"MainServices": [
{
"Id": 11,
"ServiceTypeId": 1,
"MainServiceNameAr": "تكييفات\r\n",
"MainServiceNameEn": "Air conditioning\r\n",
"SubServices": null
},
{
"Id": 12,
"ServiceTypeId": 1,
"MainServiceNameAr": "كهرباء\r\n",
"MainServiceNameEn": "Electricity\r\n",
"SubServices": null
},
{
"Id": 14,
"ServiceTypeId": 1,
"MainServiceNameAr": "سباكة",
"MainServiceNameEn": "Plumbing\r\n",
"SubServices": null
},
{
"Id": 15,
"ServiceTypeId": 1,
"MainServiceNameAr": "اجهزة منزلية\r\n",
"MainServiceNameEn": "Home appliances\r\n",
"SubServices": null
}
]
}
]
}
}
i want to implement this as a pojo(model) in my code this is my try (Edited)
ResponseModel
public class ResponseModel {
#SerializedName("Status")
public int Status;
#SerializedName("Message")
public String Message;
#SerializedName("Data")
public DataModel Data;
public int getStatus() {
return Status;
}
public void setStatus(int status) {
Status = status;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
public DataModel getData() {
return Data;
}
public void setData(DataModel data) {
this.Data = data;
}
}
DataModel
public class DataModel {
#SerializedName("Country")
private List<CountryModel> countryModels;
#SerializedName("Users")
private List<UserModel> users;
#SerializedName("Cities")
private List<CityItem> cityItems;
#SerializedName("ServiceTypes")
private List<ServiceTypeModel> serviceTypeModels;
private Map<String, Object> additionalProperties = new HashMap<String,
Object>();
public List<CityItem> getCityItems() {
return cityItems;
}
public void setCityItems(List<CityItem> cityItems) {
this.cityItems = cityItems;
}
public List<UserModel> getUsers() {
return users;
}
public void setUsers(ArrayList<UserModel> users) {
this.users = users;
}
public List<CountryModel> getCountryModels() {
return countryModels;
}
public void setCountryModels(ArrayList<CountryModel> countryModels) {
this.countryModels = countryModels;
}
public List<ServiceTypeModel> getServiceTypeModels() {
return serviceTypeModels;
}
public void setServiceTypeModels(List<ServiceTypeModel> serviceTypeModels) {
this.serviceTypeModels = serviceTypeModels;
}
public void setCountryModels(List<CountryModel> countryModels) {
this.countryModels = countryModels;
}
public void setUsers(List<UserModel> users) {
this.users = users;
}
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
}
}
ServiceTypeModel
public class ServiceTypeModel {
#SerializedName("Id")
private int id;
#SerializedName("ServiceTypeNameAr")
private String serviceTypeNameAr;
#SerializedName("ServiceTypeNameEn")
private String serviceTypeNameEn;
#SerializedName("MainServices")
private List<MainServicesModel> mainServicesList;
public List<MainServicesModel> getMainServicesList() {
return mainServicesList;
}
public void setMainServicesList(List<MainServicesModel> mainServicesList) {
this.mainServicesList = mainServicesList;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getServiceTypeNameAr() {
return serviceTypeNameAr;
}
public void setServiceTypeNameAr(String serviceTypeNameAr) {
this.serviceTypeNameAr = serviceTypeNameAr;
}
public String getServiceTypeNameEn() {
return serviceTypeNameEn;
}
public void setServiceTypeNameEn(String serviceTypeNameEn) {
this.serviceTypeNameEn = serviceTypeNameEn;
}
}
The Interface:
public interface ServiceTypeInterface {
#GET("ServiceType")
public Call<ResponseModel> GetServicesType(#Header("authorization") String token);
#GET("ServiceType/{id}")
public Call<ResponseModel> GetServiceTypeById(#Path("id") int Id, #Header("authorization") String token);
}
Adapter
public class ServiceTypeAdapter extends RecyclerView.Adapter<ServiceTypeAdapter.ServiceTypeHolder> {
private List<ResponseModel> serviceTypeModels = new ArrayList<>();
private final ServiceTypeListener listener;
private Context context;
public ServiceTypeAdapter(ServiceTypeListener listener, Context context, List<ResponseModel> serviceTypeList) {
this.listener = listener;
this.context = context;
this.serviceTypeModels = serviceTypeList;
}
#NonNull
#Override
public ServiceTypeHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_sub_service, parent, false);
return new ServiceTypeHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ServiceTypeHolder holder, int position) {
final ResponseModel ServiceType = serviceTypeModels.get(position);
holder.TxtServiceTypeName.setText(ServiceType.getData().getServiceTypeModels().get(0).getServiceTypeNameEn());
}
#Override
public int getItemCount() {
return serviceTypeModels.size();
}
public long getItemId(int position) {
return position;
}
public void setList(List<ResponseModel> serviceTypeModels) {
// serviceTypeModels = new List<ResponseModel>(serviceTypeModels.get(0).getData().getServiceTypeModels().get(0).getServiceTypeNameEn());
this.serviceTypeModels = serviceTypeModels;
notifyDataSetChanged();
}
public class ServiceTypeHolder extends RecyclerView.ViewHolder {
TextView TxtServiceTypeName;
public ServiceTypeHolder(#NonNull View itemView) {
super(itemView);
TxtServiceTypeName = itemView.findViewById(R.id.ServiceTypeName);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onServiceTypeSelected(serviceTypeModels.get(getAdapterPosition()));
}
});
}
}
public interface ServiceTypeListener {
void onServiceTypeSelected(ResponseModel serviceTypeModel);
}
}
i tried to separate them as well into two models the status, message and data which calls for the services type which is in another model.
if anything else or more clarification is needed pls don't hesitate to ask me for code or anything.
any help is really appreciated.
Thanks in advance.
you may implement pojo as this:
this class represent the top level object:
public class ResponseModel {
private Integer Status;
private String Message;
private DataModel Data;
// getters, setters, constructors
}
this class represents Data class:
public class DataModel {
private List<ServiceTypeModel> ServiceTypes;
// getters, setters, constructors
}
and this class maps with ServiceTypes
public class ServiceTypeModel {
private Long Id;
private String ServiceTypeNameAr;
private String ServiceTypeNameEn;
private List<MainServiceModel> MainServices;
// getters, setters, constructors
}
And finally this class maps with MainServices
public class MainServiceModel{
private Long Id;
private Long ServiceTypeId;
private String MainServiceNameAr;
private String MainServiceNameEn;
private List<SubServiceModel> SubServices;
// getters, setters, constructors
}
for SubServices, you have provided null so I imagine this is a List of SubServiceModel. You can implement this class like how I did for the others.
Also you can use some online tools to generate pojo of a json like this
I think the problem is with your ServiceTypeWebEntity model where you set data as a list but it's an object which has ServiceTypes key with List<ServiceTypeModel> inside, so you can try this model.
public class ServiceTypeWebEntity {
#SerializedName("Status")
private int Status;
#SerializedName("Message")
private String Message;
#SerializedName("data")
public ServiceTypes ServicesType;
public int getStatus() {
return Status;
}
public void setStatus(int status) {
Status = status;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
public ServiceTypes getServicesType() {
return ServicesType;
}
public void setServicesType(ServiceTypes servicesType) {
ServicesType = servicesType;
}
public class ServiceTypes{
#SerializedName("ServiceTypes")
public List<ServiceTypeModel> ServicesType;
public List<ServiceTypeModel> getServicesType() {
return ServicesType;
}
public void setServicesType(List<ServiceTypeModel> servicesType) {
ServicesType = servicesType;
}
}
public class ServiceTypeModel {
#SerializedName("Id")
private int id;
#SerializedName("ServiceTypeNameAr")
private String serviceTypeNameAr;
#SerializedName("ServiceTypeNameEn")
private String serviceTypeNameEn;
#SerializedName("MainServices")
private List<MainServicesModel> mainServicesList;
public List<MainServicesModel> getMainServicesList() {
return mainServicesList;
}
public void setMainServicesList(List<MainServicesModel> mainServicesList) {
this.mainServicesList = mainServicesList;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getServiceTypeNameAr() {
return serviceTypeNameAr;
}
public void setServiceTypeNameAr(String serviceTypeNameAr) {
this.serviceTypeNameAr = serviceTypeNameAr;
}
public String getServiceTypeNameEn() {
return serviceTypeNameEn;
}
public void setServiceTypeNameEn(String serviceTypeNameEn) {
this.serviceTypeNameEn = serviceTypeNameEn;
}
}
}
hope it helps.
I knew where i was wrong i was missing a small part in my main for calling the list itself here is the main for anyone who needs it or anyone facing the same issue
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
//
TestTxt = findViewById(R.id.TestTxt);
serviceTypeViewModel = ViewModelProviders.of(this).get(ServiceTypeViewModel.class);
serviceTypeViewModel.GetServiceType();
serviceTypeRecycler = findViewById(R.id.ServiceTypeRV);
// LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
// serviceTypeRecycler.setLayoutManager(layoutManager);
// serviceTypeRecycler.setItemAnimator(new DefaultItemAnimator());
// serviceTypeRecycler.setAdapter(serviceTypeAdapter);
FillListServices();
}
private void FillListServices() {
serviceTypeViewModel.ServiceTypeMutableLiveData.observe(this, new Observer<ResponseModel>() {
// Here i was trying to call the ServiceTypeModel instead
#Override
public void onChanged(ResponseModel responseModel) {
Utilities.dismissLoadingDialog();
serviceTypeModelArrayList = new ArrayList<>();
serviceTypeModelArrayList = responseModel.getData().getServiceTypeModels();
TestTxt.setText(responseModel.getData().getServiceTypeModels().get(0).getServiceTypeNameAr());
serviceTypeAdapter = new ServiceTypeAdapter(responseModel.getData().getServiceTypeModels());
LinearLayoutManager layoutManager = new LinearLayoutManager(MainCategories.this, LinearLayoutManager.HORIZONTAL, false);
serviceTypeRecycler.setLayoutManager(layoutManager);
serviceTypeRecycler.setAdapter(serviceTypeAdapter);
}
});
}

How print the entire data structure created with Composite?

I have class-Composite:
public class CompositeText implements ComponentText {
private TypeComponent type;
private String value;
private final List<ComponentText> childComponents;
private CompositeText() {
childComponents = new ArrayList<>();
}
public CompositeText(String value, TypeComponent typeComponent) {
this.value = value;
this.type = typeComponent;
childComponents = new ArrayList<>();
}
#Override
public void add(ComponentText componentText) {
childComponents.add(componentText);
}
#Override
public void remove(ComponentText componentText) {
childComponents.remove(componentText);
}
#Override
public TypeComponent getComponentType() {
return this.type;
}
#Override
public ComponentText getChild(int index) {
return childComponents.get(index);
}
#Override
public int getCountChildElements() {
return childComponents.size();
}
#Override
public int getCountAllElements() {
return childComponents.stream()
.mapToInt(ComponentText::getCountAllElements)
.sum();
}
#Override
public String toString() {
return null;
}
}
I created classes that perform the same action - parsing, parsing text into paragraphs, into sentences, into tokens, into symbols.
public class IntoParagraphParser implements ActionParser {
// call IntoSentenceParser
}
public class IntoSentenceParser implements ActionParser {
// call IntoLexemeParser
}
public class IntoLexemeParser implements ActionParser {
// call IntoSymbolParser
}
public class IntoSymbolParser implements ActionParser {
}
All data is stored in List <ComponentText> childComponents in class-Composite - CompositeText.
How to properly create a method so that it prints all the data that is inside the composite?
I think this will be the method toString() in CompositeText.
Class IntoParagraphParser look:
public class IntoParagraphParser implements ActionParser {
private static final String PARAGRAPH_SPLIT_REGEX = "(?m)(?=^\\s{4})";
private static final IntoParagraphParser paragraphParser = new IntoParagraphParser();
private static final IntoSentenceParser sentenceParser = IntoSentenceParser.getInstance();
private IntoParagraphParser() {
}
public static IntoParagraphParser getInstance() {
return paragraphParser;
}
public ComponentText parse(String text) throws TextException {
ComponentText oneParagraph;
ComponentText componentParagraph = new CompositeText(text, TypeComponent.PARAGRAPH);
String[] arrayParagraph = text.split(PARAGRAPH_SPLIT_REGEX);
for(String element: arrayParagraph) {
oneParagraph = new CompositeText(element, TypeComponent.PARAGRAPH);
oneParagraph.add(sentenceParser.parse(element));
componentParagraph.add(oneParagraph);
}
return componentParagraph;
}
}
Need #Override the method toString() in CompositeText like this:
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (ComponentText component : childComponents) {
builder.append(component.toString());
}
return builder.toString();
}
But how to write this code correctly with Stream API?
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
childComponents.stream().map(...????
return builder.toString();
}

Realm and Expected BEGIN_OBJECT but was NUMBER at path $[0].location.coordinates[0]

I'm trying to store a coordnates (array of double) using Realm-java,but I'm not able to do it.
Here is an example of json that I'm trying to parse:
{"_id":"597cd98b3af0b6315576d717",
"comarca":"string",
"font":null,
"imatge":"string",
"location":{
"coordinates":[41.64642,1.1393],
"type":"Point"
},
"marca":"string",
"municipi":"string",
"publisher":"string",
"recursurl":"string",
"tematica":"string",
"titol":"string"
}
My global object code is like that
public class Images extends RealmObject implements Serializable {
#PrimaryKey
private String _id;
private String recursurl;
private String titol;
private String municipi;
private String comarca;
private String marca;
private String imatge;
#Nullable
private Location location;
private String tematica;
private String font;
private String parentRoute;
public Location getLocation() {return location;}
public void setLocation(Location location) {this.location = location;}
public String getParentRoute() {
return parentRoute;
}
public void setParentRoute(String parentRoute) {
this.parentRoute = parentRoute;
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getFont() {
return font;
}
public void setFont(String font) {
this.font = font;
}
public String getRecursurl() {
return recursurl;
}
public void setRecursurl(String recursurl) {
this.recursurl = recursurl;
}
public String getTitol() {
return titol;
}
public void setTitol(String titol) {
this.titol = titol;
}
public String getMunicipi() {
return municipi;
}
public void setMunicipi(String municipi) {
this.municipi = municipi;
}
public String getComarca() {
return comarca;
}
public void setComarca(String comarca) {
this.comarca = comarca;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getImatge() {
return imatge;
}
public void setImatge(String imatge) {
this.imatge = imatge;
}
public String getTematica() {
return tematica;
}
public void setTematica(String tematica) {
this.tematica = tematica;
}
And Location is a composite of type and a realmlist
Location.java
public class Location extends RealmObject implements Serializable {
private String type;
private RealmList<RealmDoubleObject> coordinates;
public Location() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RealmList<RealmDoubleObject> getCoordinates() {
return coordinates;
}
public void setCoordinates(RealmList<RealmDoubleObject> coordinates) {
this.coordinates = coordinates;
}
}
RealmDoubleObject.java
public class RealmDoubleObject extends RealmObject implements Serializable{
private Double value;
public RealmDoubleObject() {
}
public Double getDoublevalue() {
return value;
}
public void setDoublevalue(Double value) {
this.value = value;
}
}
The error is com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at path $[0].location.coordinates[0] but I'm not able to figure out why this number is not "fitting" by RealmDoubleObject.
For those that not familiar with realm RealmList doesn't work and you have to build your own realm object.
Thank you. I hope to find some Realm experts here!
SOLVED:
using Gson deserializer it can be done
First we have to initialize the gson object like this
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
#Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.registerTypeAdapter(new TypeToken<RealmList<RealmDoubleObject>>() {}.getType(), new TypeAdapter<RealmList<RealmDoubleObject>>() {
#Override
public void write(JsonWriter out, RealmList<RealmDoubleObject> value) throws IOException {
// Ignore
}
#Override
public RealmList<RealmDoubleObject> read(JsonReader in) throws IOException {
RealmList<RealmDoubleObject> list = new RealmList<RealmDoubleObject>();
in.beginArray();
while (in.hasNext()) {
Double valor = in.nextDouble();
list.add(new RealmDoubleObject(valor));
}
in.endArray();
return list;
}
})
.create();
And then we have to put some other constructor method
public RealmDoubleObject(double v) {
this.value = v;
}
and this is all.
Thanks for the help #EpicPandaForce

how to implement Parcelable in android?

can you please tell me how to implement Parcelable in android? Actually I want to send an array list from one activity to another. So I google find in need to Parcelable the dot or model. But I have object of another class so how do I write in Parcelable? In other word
I have this object
DestinationStation destinationStation;
what should i write in this function public void writeToParcel
dest.writeString(destinationStation);
here is my code of both class
public class deparaturedaseboarddto implements Parcelable{
ArrayList<deparaturedaseboarddto> data;
public ArrayList<deparaturedaseboarddto> getData() {
return data;
}
public void setData(ArrayList<deparaturedaseboarddto> data) {
this.data = data;
}
#SerializedName("alertsId")
int alertsId;
#SerializedName("destExpArrival")
String destExpArrival;
#SerializedName("destSchArrival")
String destSchArrival;
#SerializedName("expDepart")
String expDepart;
#SerializedName("filteredStation")
String filteredStation;
#SerializedName("platformNo")
String platformNo;
#SerializedName("rid")
String rid;
#SerializedName("schDepart")
String schDepart;
#SerializedName("toc")
String toc;
#SerializedName("toExpArrival")
String toExpArrival;
#SerializedName("toSchArrival")
String toSchArrival;
#SerializedName("trainID")
String trainID;
#SerializedName("trainLastReportedAt")
String trainLastReportedAt;
#SerializedName("destinationStation")
DestinationStation destinationStation;
public deparaturedaseboarddto(String trainID,String toc,String trainLastReportedAt, String platformNo, String schDepart, String expDepart, int alertsId, String rid, String destSchArrival, String filteredStation, String destExpArrival, String toSchArrival, String toExpArrival,DestinationStation destinationStation){
super();
this.trainID=trainID;
this.toc=toc;
this.trainLastReportedAt=trainLastReportedAt;
this.platformNo=platformNo;
this.schDepart=schDepart;
this.expDepart=expDepart;
this.alertsId=alertsId;
this.destinationStation=destinationStation;
this.toExpArrival=toExpArrival;
this.toSchArrival=toSchArrival;
this.destExpArrival=destExpArrival;
this.filteredStation=filteredStation;
this.destSchArrival=destSchArrival;
this.rid=rid;
}
public DestinationStation getDestinationStation() {
return destinationStation;
}
public void setDestinationStation(DestinationStation destinationStation) {
this.destinationStation = destinationStation;
}
public int getAlertsId() {
return alertsId;
}
public void setAlertsId(int alertsId) {
this.alertsId = alertsId;
}
public String getDestExpArrival() {
return destExpArrival;
}
public void setDestExpArrival(String destExpArrival) {
this.destExpArrival = destExpArrival;
}
public String getDestSchArrival() {
return destSchArrival;
}
public void setDestSchArrival(String destSchArrival) {
this.destSchArrival = destSchArrival;
}
public String getExpDepart() {
return expDepart;
}
public void setExpDepart(String expDepart) {
this.expDepart = expDepart;
}
public String getFilteredStation() {
return filteredStation;
}
public void setFilteredStation(String filteredStation) {
this.filteredStation = filteredStation;
}
public String getPlatformNo() {
return platformNo;
}
public void setPlatformNo(String platformNo) {
this.platformNo = platformNo;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getSchDepart() {
return schDepart;
}
public void setSchDepart(String schDepart) {
this.schDepart = schDepart;
}
public String getToc() {
return toc;
}
public void setToc(String toc) {
this.toc = toc;
}
public String getToExpArrival() {
return toExpArrival;
}
public void setToExpArrival(String toExpArrival) {
this.toExpArrival = toExpArrival;
}
public String getToSchArrival() {
return toSchArrival;
}
public void setToSchArrival(String toSchArrival) {
this.toSchArrival = toSchArrival;
}
public String getTrainID() {
return trainID;
}
public void setTrainID(String trainID) {
this.trainID = trainID;
}
public String getTrainLastReportedAt() {
return trainLastReportedAt;
}
public void setTrainLastReportedAt(String trainLastReportedAt) {
this.trainLastReportedAt = trainLastReportedAt;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(alertsId);
dest.writeString(destExpArrival);
dest.writeString(destSchArrival);
dest.writeString(expDepart);
dest.writeString(filteredStation);
dest.writeString(platformNo);
dest.writeString(rid);
dest.writeString(schDepart);
dest.writeString(toc);
dest.writeString(toExpArrival);
dest.writeString(toSchArrival);
dest.writeString(trainID);
dest.writeString(trainLastReportedAt);
dest.writeString(destinationStation);
}
public static final Parcelable.Creator<deparaturedaseboarddto> CREATOR = new Parcelable.Creator<deparaturedaseboarddto>() {
public deparaturedaseboarddto createFromParcel(Parcel in) {
return new deparaturedaseboarddto(in);
}
public deparaturedaseboarddto[] newArray(int size) {
return new deparaturedaseboarddto[size];
}
};
private deparaturedaseboarddto(Parcel in) {
this.alertsId=in.readInt();
this.destExpArrival=in.readString();
this.destSchArrival=in.readString();
this.expDepart=in.readString();
this.filteredStation=in.readString();
this.platformNo=in.readString();
this.rid=in.readString();
this.schDepart=in.readString();
this.toc=in.readString();
this.toExpArrival=in.readString();
this.toSchArrival=in.readString();
this.trainID=in.readString();
this.trainLastReportedAt=in.readString();
}
}
destinationstation:
import com.google.gson.annotations.SerializedName;
public class DestinationStation implements Parcelable {
#SerializedName("crsCode")
String crsCode;
#SerializedName("stationName")
String stationName;
public DestinationStation(String crsCode, String stationName) {
// TODO Auto-generated constructor stub
super();
this.crsCode=crsCode;
this.stationName=stationName;
}
public String getCrsCode() {
return crsCode;
}
public void setCrsCode(String crsCode) {
this.crsCode = crsCode;
}
public String getStationName() {
return stationName;
}
public void setStationName(String stationName) {
this.stationName = stationName;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(crsCode);
dest.writeString(stationName);
}
public static final Parcelable.Creator<DestinationStation> CREATOR = new Parcelable.Creator<DestinationStation>() {
public DestinationStation createFromParcel(Parcel in) {
return new DestinationStation(in);
}
public DestinationStation[] newArray(int size) {
return new DestinationStation[size];
}
};
private DestinationStation(Parcel in) {
this.crsCode=in.readString();
this.stationName=in.readString();
}
}
I am getting error in this line
dest.writeString(destinationStation);
Could you please tell how to remove this error?

Categories