Missing object when using #SerializedName with Retrofit call - android

I'm developing an Android app which connects to a Springboot server.
The app (using okhttp3 and retrofit) calls the server which returns an array list in an object (Photo Response) below.
The list is populating but the object MediaContentGroup does not populate in any photo object even though the fields of id and title do.
I've debugged through my server to ensure that I am using the correct object names when using #SerializedName.
I'm pretty new to Android development and using springboot, so if anyone could help me to understand why the MediaContentGroup object is always null, I would really appreciate it.
Is there any possible way I've set it to only accept Strings??
Thanks
public class PhotoResponse {
#SerializedName("photoFeed")
#Expose
private PhotoFeed photoFeed;
public PhotoFeed getPhotoFeed() {
return photoFeed;
}
}
public class PhotoFeed {
#SerializedName("photoList")
#Expose
private List<Photo> photoList = new ArrayList<>();
public List<Photo> getPhotoList() {
return photoList;
}
}
public class Photo {
public final static int HD_720_WIDTH = 1280;
public final static int HD_720_HEIGHT = 720;
#SerializedName("id")
#Expose
private String id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("mediaContentGroup")
#Expose
private MediaContentGroup mediaContentGroup;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setMediaContentGroup(MediaContentGroup mediaContentGroup){
this.mediaContentGroup = mediaContentGroup;
}
public MediaContentGroup getMediaContentGroup(){
return this.mediaContentGroup;
}
public String getImageUrl() {
return mediaContentGroup.getImages().get(0).getUrl();
}
public String getThumbUrl() {
return mediaContentGroup.getThumbnails().get(0).getUrl();
}
}
public class MediaContentGroup {
#SerializedName("images")
#Expose
public List<MediaContent> images = new ArrayList<>();
public void setImages(List<MediaContent> images){ this.images = images;}
public List<MediaContent> getImages() {
return images;
}
#SerializedName("thumbnails")
#Expose
public List<Thumbnail> thumbnails = new ArrayList<>();
public void setThumbnails(List<Thumbnail> thumbnails){ this.thumbnails = thumbnails;}
public List<Thumbnail> getThumbnails() {
return thumbnails;
}
}
public class Thumbnail {
#SerializedName("url")
#Expose
private String url;
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}

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

add object into GSON array android studio

hey guys im using android's gson library to parse my JSON. everything is working fine in that I have that selected goal array sometimes it is full of values and sometimes it is an empty array. when array is empty I want to push an object init when I try to add its index
selected_goal.add(INDEX,VALUE)
I want to push an object at the place of value please help me how can I do it…
this is my pojo:
public class SelectedGoal {
#SerializedName("id")
#Expose
private String id;
#SerializedName("goal_name")
#Expose
private String goalName;
#SerializedName("image")
#Expose
private String image;
#SerializedName("position")
#Expose
private String position;
#SerializedName("athlete_id")
#Expose
private String athleteId;
#SerializedName("coach_id")
#Expose
private String coachId;
#SerializedName("current_goal_id")
#Expose
private String currentGoalId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGoalName() {
return goalName;
}
public void setGoalName(String goalName) {
this.goalName = goalName;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getAthleteId() {
return athleteId;
}
public void setAthleteId(String athleteId) {
this.athleteId = athleteId;
}
public String getCoachId() {
return coachId;
}
public void setCoachId(String coachId) {
this.coachId = coachId;
}
public String getCurrentGoalId() {
return currentGoalId;
}
public void setCurrentGoalId(String currentGoalId) {
this.currentGoalId = currentGoalId;
}
}
selected_goal.add(INDEX,new SelectedGoal());
EDIT- To set values, make constuctor in your SelectedGoal class like.
public SelectedGoal(String id, String goalName, String image, String
position, String athleteId, String coachId, String currentGoalId) {
this.id = id;
this.goalName = goalName;
this.image = image;
this.position = position;
this.athleteId = athleteId;
this.coachId = coachId;
this.currentGoalId = currentGoalId;
}
finally add your object into list like..
selected_goal.add(INDEX,new SelectedGoal(id,goalName,image,position,athleteId,coachId,currentGoalId));

Android Retrofit consuming API not working

I'm working on an Android project and I'm using retrofit to fetch JSON data. My JSON look like this.
{
"status":"ok",
"count":1,
"count_total":1,
"pages":1,
"posts":[
{
"id":4,
"type":"post",
"slug":"my news",
"status":"publish",
"title":"test news title goes here",
"title_plain":"test news title goes here",
"content":"<p>news title goes<\/span><\/p>\n",
"date":"2018-05-12 20:00:51",
"modified":"2018-05-12 20:00:51"
}
]
}
My model class -Article.java
public class Article {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("status")
#Expose
private String status;
#SerializedName("title")
#Expose
private String title;
#SerializedName("title_plain")
#Expose
private String titlePlain;
#SerializedName("content")
#Expose
private String content;
#SerializedName("date")
#Expose
private String date;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitlePlain() {
return titlePlain;
}
public void setTitlePlain(String titlePlain) {
this.titlePlain = titlePlain;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
I'm calling to retrofit method like this and already added a dialog box for loading. But I'm not getting response from the API. (It works perfectly when I'm typing on the browser)
NewsService service = RetrofitClient.getRetrofitInstance().create(NewsService.class);
Call<List<Article>> call = service.getNewestArticles();
call.enqueue(new Callback<List<Article>>() {
#Override
public void onResponse(Call<List<Article>> call, Response<List<Article>> response) {
dialog.dismiss();
generateDataList(response.body());
}
#Override
public void onFailure(Call<List<Article>> call, Throwable t) {
}
});
private void generateDataList(List<Article> articles) {
lstNews.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
lstNews.setLayoutManager(layoutManager);
adapter = new ListNewsAdapter(articles,getActivity().getBaseContext());
adapter.notifyDataSetChanged();
lstNews.setAdapter(adapter);
lstNews.setAdapter(adapter);
}
I'm new to retrofit. Could someone please help me to fix this issue?
You're not actually loading a list (array) of articles but an object conatining a list of articles, so you need 2 model classes :
public class ArticleResponse {
#SerializedName("status")
#Expose
private String status;
#SerializedName("count")
#Expose
private int count;
#SerializedName("count_total")
#Expose
private int countTotal;
#SerializedName("pages")
#Expose
private int pages;
#SerializedName("posts")
#Expose
private List<Article> articles;
//getter/Setter
//...
}
Your retrofit service should return that ArticleResponse instead, then you can get your article array through articles getter from your model
NewsService service = RetrofitClient.getRetrofitInstance().create(NewsService.class);
Call<ArticleResponse> call = service.getNewestArticles();
call.enqueue(new Callback<ArticleResponse>() {
#Override
public void onResponse(Call<ArticleResponse> call, Response<ArticleResponse> response) {
dialog.dismiss();
generateDataList(response.body().getArticles());
}
#Override
public void onFailure(Call<ArticleResponse> call, Throwable t) {
Log.w( t );
}
});

Realm: How to query with many to many field

I recently heard about Realm for android (also available for iOS) in this talk by Joaquim Verques . Very interesting and very powerful tool for persistent data.
I decided to give it a try after the video, researching and reading the documentation.
I found it very easy to use and set up but i end up stuck in the middle of my project because i couldn't manage to successfully make a query with many to many relationships.
I have created a small example for this topic.
My models:
public class Feed extends RealmObject {
#PrimaryKey
private int id;
private String title;
private String description;
private String link;
private Terms terms;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Terms getTerms() {
return terms;
}
public void setTerms(Terms terms) {
this.terms = terms;
}
}
public class Terms extends RealmObject {
private String tag;
private RealmList<Category> categories;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public RealmList<Category> getCategories() {
return categories;
}
public void setCategories(RealmList<Category> categories) {
this.categories = categories;
}
}
public class Category extends RealmObject {
#PrimaryKey
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So far so good, now im going to save a list of feeds to realm (make it persistent) and then try to make some query.
public static void test(final Context context,final List<Feed> feedList) {
Realm realm = null;
try {
realm = Realm.getInstance(context);
realm.beginTransaction();
realm.copyToRealmOrUpdate(feedList);
realm.commitTransaction();
RealmResults<Feed> realmResults = realm.where(Feed.class).findAll();// return me all feeds
RealmResults<Feed> realmResults1 = realm.where(Feed.class).equalTo("id", 1).findAll(); // return feed with id 1
RealmResults<Feed> realmResults2 = realm.where(Feed.class).equalTo("terms.tag", "tech").findAll(); // return feeds //with tag = "tech"
RealmResults<Feed> realmResults3 = realm.where(Feed.class).equalTo("terms.category.name", "test").findAll(); //exception here
}
} catch (Exception e) {
//Empty
Log.d("Test","",e);
} finally {
if (realm != null)
realm.close();
}
}
}
Everything run well untill the last query and i get this exception:"java.lang.IllegalArgumentException: Invalid query: category does not refer to a class."
So my question is How do i do that kind of query successfully, as i will like realm to return me every feed with terms which has at least 1 category with name = "test"
Thank you very much
Your field is called "categories" and not "category". The third query should be:
RealmResults<Feed> realmResults3 = realm.where(Feed.class).equalTo("terms.categories.name", "test").findAll();

Categories

Resources