how to handle a JSON array object using retrofit? - android

I am not so new to Android, but started using retrofit today, I was able to clear all errors, now the response body returns null. I know its something to do with the way my class is set up. I have no idea how to handle an array with arrays. Any help would be appreciated. Thanks
[
My Interface
#GET("/web-api.php?route=feed/web_api/products")
Call<Product> loadProducts(#Query("category") Integer id, #Query("key") String apiKey);
Class
public class Product implements Serializable {
#SerializedName("id")
private long mId;
#SerializedName("name")
private String mname;
#SerializedName("description")
private String mText;
#SerializedName("price")
private Double mprice;
#SerializedName("href")
private String mproductURL;
#SerializedName("thumb")
private String mImageURL;
public Product(long mId, String mname, String mText, Double mprice, String mproductURL, String mImageURL) {
this.mId = mId;
this.mname = mname;
this.mText = mText;
this.mprice = mprice;
this.mproductURL = mproductURL;
this.mImageURL = mImageURL;
}
public long getmId() {
return mId;
}
public void setmId(long mId) {
this.mId = mId;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
public Double getMprice() {
return mprice;
}
public void setMprice(Double mprice) {
this.mprice = mprice;
}
public String getMproductURL() {
return mproductURL;
}
public void setMproductURL(String mproductURL) {
this.mproductURL = mproductURL;
}
public String getmImageURL() {
return mImageURL;
}
public void setmImageURL(String mImageURL) {
this.mImageURL = mImageURL;
}
#Override
public String toString() {
return mText;
}
}

Just define a Super class -
public class ResponseDS{
public boolean success;
public Product[] products;
}
And use ResponseDS instead of Product class -
#GET("/web-api.php?route=feed/web_api/products")
Call<ResponseDS> loadProducts(#Query("category") Integer id, #Query("key") String apiKey);
Hope it will help :)

Related

Refer to Object from server response

On the server there is (as I understand it) an object. It has 2 values ​​- the text and the color of this text. So - I need to get this text and color. At the moment everything is displayed together - TextView is passed the value [{"text": "WE RETURN 10% BONUSES", "textColor": "# 4c82a6"}] ,.
I need to get these values ​​separately
"tag": [
{
"text": "ВЕРНЕМ 10% БОНУСАМИ",
"textColor": "#4c82a6"
}
],
Model
public class Item {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("image")
#Expose
private String image;
#SerializedName("isFavorite")
#Expose
private boolean isFavorite;
#SerializedName("prices")
#Expose
private Prices prices;
#SerializedName("full_set_prices")
#Expose
private Object fullSetPrices;
#SerializedName("isBestPrice")
#Expose
private boolean isBestPrice;
#SerializedName("tag")
#Expose
private Object tag;
#SerializedName("articul")
#Expose
private String articul;
#SerializedName("rating")
#Expose
private double rating;
#SerializedName("numberOfReviews")
#Expose
private int numberOfReviews;
#SerializedName("statusText")
#Expose
private String statusText;
#SerializedName("isAvailable")
#Expose
private boolean isAvailable;
#SerializedName("images")
#Expose
private List<String> images = null;
#SerializedName("categoryId")
#Expose
private String categoryId;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getImage() {
return image;
}
public boolean isIsFavorite() {
return isFavorite;
}
public Prices getPrices() {
return prices;
}
public Object getFullSetPrices() {
return fullSetPrices;
}
public boolean isIsBestPrice() {
return isBestPrice;
}
public Object getTag() {
return tag;
}
public void setTag(Object tag) {
this.tag = tag;
}
public String getArticul() {
return articul;
}
public void setArticul(String articul) {
this.articul = articul;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public int getNumberOfReviews() {
return numberOfReviews;
}
public void setNumberOfReviews(int numberOfReviews) {
this.numberOfReviews = numberOfReviews;
}
public String getStatusText() {
return statusText;
}
public void setStatusText(String statusText) {
this.statusText = statusText;
}
public boolean isIsAvailable() {
return isAvailable;
}
public void setIsAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
}
You could create another POJO for the tag instead of using Object.
public class Item {
...
#SerializedName("tag")
#Expose
private Tag tag;
...
}
public class Tag {
#SerializedName("text")
#Expose
private String text;
#SerializedName("textColor")
#Expose
private String textColor;
}
Then you can access the new values with item.getTag().getText(). Or if you'd rather make it appear that the two Tag fields are part of Item, you can create methods that delegate to Tag:
public class Item {
...
public String getText() {
return this.tag.getText();
}
public String getTextColor() {
return this.tag.getTextColor();
}
...
}

Java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY when want to get data into recyclerview

I have a json. I have to get source_url into my recyclerView -
[{
"id":3110,
"date":"2020-05-07T18:33:44",
"date_gmt":"2020-05-07T18:33:44",
"modified":"2020-05-07T18:35:37",
"modified_gmt":"2020-05-07T18:35:37",
"_embedded":{
"wp:featuredmedia":[
{
"id":3111,
"date":"2020-05-07T18:33:08",
"slug":"prof-dr-abul-khair",
"source_url":"https:\/\/www.healthmen.com.bd\/wpcontent\/uploads\/2020\/05\/Prof.-Dr.-Abul-Khair-scaled.jpg"
}]
}
}]
I want to get source_url from this JSON
But, here is an array wp:featuredmedia. So that, I followed this process-
Created a class named FeaturedMedia -
public class FeaturedMedia {
#SerializedName("source_url")
#Expose
private String souceurl;
public String getSourceurl(){
return sourceurl;
}
}
Then, I created another class named MediaDetails where I take the FeaturedMedia as a List-
public class MediaDetails{
#SerializedName("wp:featuredmedia")
List<FeaturedMedia> featureMediaList;
public List<FeaturedMedia> getFeaturedMediaList(){
return featuredMediaList;
}}
Then the Model Class-
public class Model{
#SerializedName("id")
#Expose
int id;
#SerializedName("_embedded")
#Expose
MediaDetalis embedded;
public int getId(){
return id;
}
public MediaDetails getEmbedded(){
return embedded;
}}
After all, I created RecyclerViewAdapter to get the data-
public CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomAdapterHolder{
List<Model> modelList;
public void onBindViewHolder(#NonNull CustomAdapterHolder holder, int position){
final Model model=modelList.get(position);
int id= model.getId():
String embedded= String.valurOf(model.getEmbedded.getFeaturedMediaList());
}
But, embedded can not get the source_url value. I completed this CustomAdapter. Here I just presented needed code of that adapter. How can I get the source_url value in this RecyclerView?
Your POJO class will be (Respect to given JSON)
public class Model {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("date")
#Expose
private String date;
#SerializedName("date_gmt")
#Expose
private String dateGmt;
#SerializedName("modified")
#Expose
private String modified;
#SerializedName("modified_gmt")
#Expose
private String modifiedGmt;
#SerializedName("_embedded")
#Expose
private Embedded embedded;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDateGmt() {
return dateGmt;
}
public void setDateGmt(String dateGmt) {
this.dateGmt = dateGmt;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
public String getModifiedGmt() {
return modifiedGmt;
}
public void setModifiedGmt(String modifiedGmt) {
this.modifiedGmt = modifiedGmt;
}
public Embedded getEmbedded() {
return embedded;
}
public void setEmbedded(Embedded embedded) {
this.embedded = embedded;
}
}
Then Embedded class
public class Embedded {
#SerializedName("wp:featuredmedia")
#Expose
private List<WpFeaturedmedium> wpFeaturedmedia = null;
public List<WpFeaturedmedium> getWpFeaturedmedia() {
return wpFeaturedmedia;
}
public void setWpFeaturedmedia(List<WpFeaturedmedium> wpFeaturedmedia) {
this.wpFeaturedmedia = wpFeaturedmedia;
}
}
Then WpFeaturedmedium
public class WpFeaturedmedium {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("date")
#Expose
private String date;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("source_url")
#Expose
private String sourceUrl;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getSourceUrl() {
return sourceUrl;
}
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
}
Check - How to create POJO class

Trying to use GSON with OpenWeather API

I'm trying to use GSON with my OpenWeatherMap API. I was able to parse my JSON into the following code:
public class List {
#SerializedName("dt")
#Expose
private Integer dt;
#SerializedName("main")
#Expose
private Main main;
#SerializedName("weather")
#Expose
private java.util.List<Weather> weather = null;
#SerializedName("clouds")
#Expose
private Clouds clouds;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("rain")
#Expose
private Rain rain;
#SerializedName("sys")
#Expose
private Sys sys;
#SerializedName("dt_txt")
#Expose
private String dtTxt;
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public java.util.List<Weather> getWeather() {
return weather;
}
public void setWeather(java.util.List<Weather> weather) {
this.weather = weather;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Rain getRain() {
return rain;
}
public void setRain(Rain rain) {
this.rain = rain;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public String getDtTxt() {
return dtTxt;
}
public void setDtTxt(String dtTxt) {
this.dtTxt = dtTxt;
}
}
public class Main {
#SerializedName("temp")
#Expose
private Double temp;
#SerializedName("temp_min")
#Expose
private Double tempMin;
#SerializedName("temp_max")
#Expose
private Double tempMax;
#SerializedName("pressure")
#Expose
private Double pressure;
#SerializedName("sea_level")
#Expose
private Double seaLevel;
#SerializedName("grnd_level")
#Expose
private Double grndLevel;
#SerializedName("humidity")
#Expose
private Integer humidity;
#SerializedName("temp_kf")
#Expose
private Integer tempKf;
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
public Double getTempMin() {
return tempMin;
}
public void setTempMin(Double tempMin) {
this.tempMin = tempMin;
}
public Double getTempMax() {
return tempMax;
}
public void setTempMax(Double tempMax) {
this.tempMax = tempMax;
}
public Double getPressure() {
return pressure;
}
public void setPressure(Double pressure) {
this.pressure = pressure;
}
public Double getSeaLevel() {
return seaLevel;
}
public void setSeaLevel(Double seaLevel) {
this.seaLevel = seaLevel;
}
public Double getGrndLevel() {
return grndLevel;
}
public void setGrndLevel(Double grndLevel) {
this.grndLevel = grndLevel;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Integer getTempKf() {
return tempKf;
}
public void setTempKf(Integer tempKf) {
this.tempKf = tempKf;
}
}
public class Weather {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("main")
#Expose
private String main;
#SerializedName("description")
#Expose
private String description;
#SerializedName("icon")
#Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
I've been searching online and on here and I have been unable to find how exactly to use GSON with my code which is:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_weather_app, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL));
requestJsonObject();
return view;
}
private void requestJsonObject (){
}
How exactly do I add the GSON parsing to my code? I only need the temperature, max, min, weather and humidity?
EDIT:
Here is some more info. I plan on using a normal http connection with an apikey to get my information. I am also planning on using RecyclerView and here is that code:
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.CurrentRecycler> {
List<Weather> mCurrentWeatherDataList;
public static class CurrentRecycler extends RecyclerView.ViewHolder{
public TextView location;
public TextView currentTemp;
public TextView currentHumidity;
public TextView currentDescription;
public ImageView currentIcon;
public CurrentRecycler (View view) {
super (view);
location = (TextView) view.findViewById(R.id.current_city_location);
currentTemp = (TextView) view.findViewById(R.id.current_temperature);
currentHumidity = (TextView) view.findViewById(R.id.current_humidity);
currentDescription = (TextView) view.findViewById(R.id.current_weather_description);
currentIcon = (ImageView) view.findViewById(R.id.current_weather_icon);
}
}
public RecyclerViewAdapter (List<Weather> mCurrentWeatherDataList) {
this.mCurrentWeatherDataList = mCurrentWeatherDataList;
}
#Override
public CurrentRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final CurrentRecycler currentRecycler = new CurrentRecycler(view);
return currentRecycler;
}
#Override
public void onBindViewHolder( CurrentRecycler holder, int position) {
final Weather currentRecycler = mCurrentWeatherDataList.get(position);
holder.location.setText(currentRecycler.getDefaultLocation());
holder.currentTemp.setText((currentRecycler.getDefaultCurrentTemp()));
holder.currentHumidity.setText(currentRecycler.getDefaultHumidity());
holder.currentDescription.setText(currentRecycler.getDefaultDescription());
}
#Override
public int getItemCount() {
return mCurrentWeatherDataList.size();
}
}
In your requestJsonObject method, use volley or okhttp to fetch the weather data from API.
Once you get the data as a String, you can use the following code:
List list = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(str, List.class);
Main main = list.getDt();
main.getTemp();
main.getTempMin();
main.getTempMax();
str means your api response data. List means your first entity class.
Moreover, I strongly recommend you to rename your class name, never try to use the reserved name of Java, make them meaningful.

Clear a Model class

I have a model class "JobPostBean" which I'm initiating in another model class and adding data using the second model class. I would like to clear any data which gets saved in the "JobPostBean" class. Is there any way to clear it either in "JobPostBean" class or in the second model class where its initialised? I would prefer to clear it using a single method rather than setting every item in the "JobPostBean" class to null.
public class BidNextJobDataModel {
private static BidNextJobDataModel ourInstance = new BidNextJobDataModel();
public static BidNextJobDataModel getInstance() {
return ourInstance;
}
private BidNextJobDataModel() {
}
public UserBean userBean;
// Here I initialised the class
public JobPostBean jobPostBean = new JobPostBean();
public ArrayList<FilterModel> filterModelArrayList = new ArrayList<FilterModel>();
public ArrayList<FilterModel> notificationModelArrayList = new ArrayList<FilterModel>();
public ArrayList<FilterModel> chooseCategoryArrayList = new ArrayList<FilterModel>();
public ArrayList<JobsBean> jobsBeanArrayList = new ArrayList<JobsBean>();
}
public class JobPostBean {
private String jobtype="";
private String days="";
private String hour="";
private String title="";
private String category="";
private String categorytxt="";
private String description="";
private String price="";
private String duration="";
private String is_certified="";
private String is_insure="";
private String is_experience="";
private String address="";
private String name="";
private String image="";
private String date="";
private String pricetype="";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getJobtype() {
return jobtype;
}
public void setJobtype(String jobtype) {
this.jobtype = jobtype;
}
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
public String getHour() {
return hour;
}
public void setHour(String hour) {
this.hour = hour;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategorytxt() {
return categorytxt;
}
public void setCategorytxt(String categorytxt) {
this.categorytxt = categorytxt;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getIs_certified() {
return is_certified;
}
public void setIs_certified(String is_certified) {
this.is_certified = is_certified;
}
public String getIs_insure() {
return is_insure;
}
public void setIs_insure(String is_insure) {
this.is_insure = is_insure;
}
public String getIs_experience() {
return is_experience;
}
public void setIs_experience(String is_experience) {
this.is_experience = is_experience;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPricetype() {
return pricetype;
}
public void setPricetype(String pricetype) {
this.pricetype = pricetype;
}
}
public ArrayList<JobPostBean > al_JobPostBean = new ArrayList<JobPostBean >(); // Declare as global
At first Hold Data in ArrayList .If you want delete all data then You can Clear ArrayList
al_JobPostBean.clear();
The clear() method removes all the elements of ArrayList .

Sugar ORM doesnt store data

I am using Sugar ORM 1.3.1 and i am trying to save the following objects
public class Article extends SugarRecord<Article> implements Serializable {
#JsonProperty("Categories")
private List<Category> categories = new ArrayList<Category>();
#JsonProperty("Contents")
private List<Content> contents = new ArrayList<Content>();
#JsonProperty("Country")
private CountryRelated country;
#JsonProperty("Description")
private String description;
#JsonProperty("ExpiryDate")
private String expiryDate;
#JsonProperty("ExtraFields")
private List<ExtraField> extraFields = new ArrayList<ExtraField>();
#JsonProperty("Identifier")
private int identifier;
#JsonProperty("ImageURL")
private String imageURL;
#JsonProperty("Name")
private String name;
#JsonProperty("PortalID")
private int portalID;
#JsonProperty("PublishDate")
private String publishDate;
#JsonProperty("Region")
private Region region;
#JsonProperty("Related")
private List<Related> related = new ArrayList<Related>();
#JsonProperty("Newsbite")
private boolean newsbite;
#JsonProperty("ShareURL")
private String shareURL;
#JsonProperty("Tags")
private List<Tag> tags = new ArrayList<Tag>();
#JsonProperty("Type")
private int type;
public Article() {
}
public Article(List<Category> categories, List<Content> contents, List<ExtraField> extraFields, CountryRelated country, String description, String expiryDate, int identifier, String imageURL, String name, boolean newsbite, int portalID, String publishDate, Region region, List<Related> related, String shareURL, List<Tag> tags, int type) {
this.categories = categories;
this.contents = contents;
this.extraFields = extraFields;
this.country = country;
this.description = description;
this.expiryDate = expiryDate;
this.identifier = identifier;
this.imageURL = imageURL;
this.name = name;
this.newsbite = newsbite;
this.portalID = portalID;
this.publishDate = publishDate;
this.region = region;
this.related = related;
this.shareURL = shareURL;
this.tags = tags;
this.type = type;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Content> getContents() {
return contents;
}
public void setContents(List<Content> contents) {
this.contents = contents;
}
public List<ExtraField> getExtraFields() {
return extraFields;
}
public void setExtraFields(List<ExtraField> extraFields) {
this.extraFields = extraFields;
}
public CountryRelated getCountry() {
return country;
}
public void setCountry(CountryRelated country) {
this.country = country;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(String expiryDate) {
this.expiryDate = expiryDate;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isNewsbite() {
return newsbite;
}
public void setNewsbite(boolean newsbite) {
this.newsbite = newsbite;
}
public int getPortalID() {
return portalID;
}
public void setPortalID(int portalID) {
this.portalID = portalID;
}
public String getPublishDate() {
return publishDate;
}
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Related> getRelated() {
return related;
}
public void setRelated(List<Related> related) {
this.related = related;
}
public String getShareURL() {
return shareURL;
}
public void setShareURL(String shareURL) {
this.shareURL = shareURL;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
Category.class
public class Category extends SugarRecord<Category> implements Serializable {
#JsonProperty("Identifier")
private int identifier;
#JsonProperty("Name")
private String name;
public constructor + getters and setters }
Content.class and CountryRelated.class have same structure
after i do article.save() my lists doesnt save . Am i doing something wrong or it doesnt save lists at all ???
I few things to look at.
First. I do not believe that the database will handle a column with the type of List or a type of other Object. When I tried running your code, I received:
Class cannot be read from Sqlite3 database. Please check the type of field categories(java.util.List)
These should be types the database can store. Try serializing your List(s) to Strings to insert them in the db. You can try doing this in your getter and setter. The setter takes the list of objects and converts it to a serialized String, the getter takes the serialized String and converts it back to a list of objects.
In the instance of SugarOrm, you can reference another table and it will create a relationship outlined here:
http://satyan.github.io/sugar/creation.html#why
Notice the "Author" type is just referencing a record from another table in the database.
Second I usually try and set my default values inside my default constructor. so something like:
... property declarations...
public Article() {
this.name = "Default Value";
}
Hope this helps you finish troublshooting!

Categories

Resources