How I can map this three class into Realm? - android

I have 3 (POJO) classes which I have requested from NewsApi by Retrofit. I should take this class and make a RealmObject. How can I do it?
Here this classes :
public class Source {
#SerializedName("id") #Expose private Object id;
#SerializedName("name") #Expose private String name;
public Object getId() { return id;}
public void setId(Object id) { this.id = id;}
public String getName() { return name;}
public void setName(String name) { this.name = name;}
}
Second class :
public class Article {
#SerializedName("source") #Expose private Source source;
#SerializedName("author") #Expose private String author;
#SerializedName("title") #Expose private String title;
#SerializedName("description") #Expose private String description;
#SerializedName("url") #Expose private String url;
#SerializedName("urlToImage") #Expose private String urlToImage;
#SerializedName("publishedAt") #Expose private String publishedAt;
public Source getSource() {return source;}
public void setSource(Source source) { this.source = source;}
public String getAuthor() { return author;}
public void setAuthor(String author) { this.author = author;}
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 getUrl() { return url;}
public void setUrl(String url){this.url = url;}
public String getUrlToImage() {return urlToImage;}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
}
Third class
public class ArticlesResponse {
#SerializedName("status") private String status;
#SerializedName("sortBy") private String sortBy;
#SerializedName("source") private String source;
#SerializedName("articles") private List<Article> articles;
public ArticlesResponse() {}
public String getStatus() {return status;}
public void setStatus(String status) { this.status = status;}
public String getSortBy() { return sortBy;}
public void setSortBy(String sortBy) {this.sortBy = sortBy;}
public String getSource() { return source;}
public void setSource(String source) { this.source = source;}
public List<Article> getArticles() { return articles;}
public void setArticles(List<Article> articles) {this.articles = articles;}
public ArticlesResponse getArticleResponse() { return null;}
}
I thought that I should make three classes which would extentnds RealmObject.
class Source : extends RealmObject {}
class Article : extends RealmObject {and here RealmList<Source> }
class ArticleResponse : extends RealmObject {and here RealmList<Article>}
but what about fields which are Objects?
private Object id;

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

Model structure to parse JSON with Retrofit [duplicate]

This question already has answers here:
Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?
(2 answers)
GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?
(11 answers)
Closed 4 years ago.
I have the following JSON structure:
[
{
"id":1,
"name":"car",
"elements":[
{
"id":1,
"name":"price",
"type":"textField",
"constraints":"blablabla"
},
{
"id":2,
"name":"color",
"type":"textField",
"constraints":"blablabla"
},
{
"id":3,
"name":"images",
"type":"image",
"constraints":"blablabla"
}
]
}
]
And I have the following models:
public class Product {
private Long id;
private String name;
#Expose
private Element elements;
public Product(Long id, String name, Element elements) {
this.id = id;
this.name = name;
this.elements = elements;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public Element getElements() {
return elements;
}
}
public class Element {
private Long id;
private String name;
private String type;
private String constraints;
public Element(Long id, String name, String constraints, String type) {
this.id = id;
this.type=type;
this.name = name;
this.constraints = constraints;
}
public String getType() {
return type;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getConstraints() {
return constraints;
}
}
The Elements model is which I have problems, I am getting the following error:
ERROR: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 35 path $[0].elements
How can I change the model to make it work? I tried to change the elements in Product class to JSONObject array but when I wanted to parse, it was empty.
You need to modify your POJOs like this:
Element.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Element {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("type")
#Expose
private String type;
#SerializedName("constraints")
#Expose
private String constraints;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getConstraints() {
return constraints;
}
public void setConstraints(String constraints) {
this.constraints = constraints;
}
}
Product.java
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Product {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("elements")
#Expose
private List<Element> elements = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
}
P.S: You should use 'http://www.jsonschema2pojo.org/' website for generating POJO automatically from the JSON string you provide to it.
I hope this helps.
I think you try to put an array of Elements into "private Element elements" which is a single object
Change your pojo with this. Also you can add your respective constructor which you require.
public class Element {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("type")
#Expose
private String type;
#SerializedName("constraints")
#Expose
private String constraints;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getConstraints() {
return constraints;
}
public void setConstraints(String constraints) {
this.constraints = constraints;
}
}
public class Product {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("elements")
#Expose
private List<Element> elements = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
}
in json you have list of Element and in the model you declared Element as an Object
change this private Element elements; to List of Element
Try this pojo or you can make from this link
private String id;
private String name;
private ArrayList<Elements> elements;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public ArrayList<Elements> getElements ()
{
return elements;
}
public void setElements (ArrayList<Elements> elements)
{
this.elements = elements;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+", name = "+name+", elements = "+elements+"]";
}
public class Elements
{
private String id;
private String name;
private String constraints;
private String type;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getConstraints ()
{
return constraints;
}
public void setConstraints (String constraints)
{
this.constraints = constraints;
}
public String getType ()
{
return type;
}
public void setType (String type)
{
this.type = type;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+", name = "+name+", constraints = "+constraints+",
type = "+type+"]";
}
}

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 );
}
});

how to handle a JSON array object using retrofit?

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 :)

Categories

Resources