This is my jsonarray.
[
{
"id": 3,
"title": "Best Seller",
"promotedProducts": [
{
"product": {
"id": 4208,
"name": "Gents T-Shirt With Navy Blue Collar cuff",
"reviewList": [],
"productDetail": {
"id": 4207,
"length": 33,
"breadth": 27
},
"attributeList": [
{
"id": 1,
"productId": 4208
}
]
}
},
{
"product": {
"id": 4208,
"name": "Gents T-Shirt With Navy Blue Collar cuff",
"reviewList": [],
"productDetail": {
"id": 4207,
"length": 33,
"breadth": 27
},
"attributeList": [
{
"id": 1,
"productId": 4208
}
]
}
}
]
}
]
I had created Homecollection class for it.also added following code for parsing.I had also created subclasses for product,promotedProducts,productDetail,attributeList,images.its give me as reponse of two items but other details are coming empty
Gson gson = new Gson();
HomeProducts homeProducts = HomeProducts.getInstance();
List<HomeCollections> collectionList = new ArrayList<HomeCollections>();
collectionList = Arrays.asList(gson.fromJson(response.toString(), HomeCollections[].class));
Create a Model class like this.
public class ProductDetail
{
public int id { get; set; }
public int length { get; set; }
public int breadth { get; set; }
}
public class AttributeList
{
public int id { get; set; }
public int productId { get; set; }
}
public class Product
{
public int id { get; set; }
public string name { get; set; }
public List<object> reviewList { get; set; }
public ProductDetail productDetail { get; set; }
public List<AttributeList> attributeList { get; set; }
}
public class PromotedProduct
{
public Product product { get; set; }
}
public class HomeCollections
{
public int id { get; set; }
public string title { get; set; }
public List<PromotedProduct> promotedProducts { get; set; }
}
Now use the GSON like this. Here url is the source link.You will get the response as a model. Now
response.promotedProducts will give you all list of items.
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
HomeCollections response = gson.fromJson(reader, HomeCollections.class);
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
#Generated("org.jsonschema2pojo")
public class AttributeList {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("productId")
#Expose
private Integer productId;
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The productId
*/
public Integer getProductId() {
return productId;
}
/**
*
* #param productId
* The productId
*/
public void setProductId(Integer productId) {
this.productId = productId;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
#Generated("org.jsonschema2pojo")
public class Example {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("promotedProducts")
#Expose
private List<PromotedProduct> promotedProducts = new ArrayList<PromotedProduct>();
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The promotedProducts
*/
public List<PromotedProduct> getPromotedProducts() {
return promotedProducts;
}
/**
*
* #param promotedProducts
* The promotedProducts
*/
public void setPromotedProducts(List<PromotedProduct> promotedProducts) {
this.promotedProducts = promotedProducts;
}
}
-----------------------------------com.example.Product.java-----------------------------------
package com.example;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
#Generated("org.jsonschema2pojo")
public class Product {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("reviewList")
#Expose
private List<Object> reviewList = new ArrayList<Object>();
private ProductDetail productDetail;
private List<AttributeList> attributeList = new ArrayList<AttributeList>();
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<Object> getReviewList() {
return reviewList;
}
public void setReviewList(List<Object> reviewList) {
this.reviewList = reviewList;
}
public ProductDetail getProductDetail() {
return productDetail;
}
public void setProductDetail(ProductDetail productDetail) {
this.productDetail = productDetail;
}
public List<AttributeList> getAttributeList() {
return attributeList;
}
public void setAttributeList(List<AttributeList> attributeList) {
this.attributeList = attributeList;
}
}
-----------------------------------com.example.ProductDetail.java-----------------------------------
package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ProductDetail {
private Integer id;
private Integer length;
private Integer breadth;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public Integer getBreadth() {
return breadth;
}
public void setBreadth(Integer breadth) {
this.breadth = breadth;
}
}
-----------------------------------com.example.PromotedProduct.java-----------------------------------
package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class PromotedProduct {
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
use this classes to get this data
You can use the following website to parse:
jsonschema2pojo
A version would be:
public class PromotedProduct {
#SerializedName("product")
#Expose
private Product product;
/**
*
* #return
* The product
*/
public Product getProduct() {
return product;
}
/**
*
* #param product
* The product
*/
public void setProduct(Product product) {
this.product = product;
}
}
ProductDetail:
public class ProductDetail {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("length")
#Expose
private Integer length;
#SerializedName("breadth")
#Expose
private Integer breadth;
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The length
*/
public Integer getLength() {
return length;
}
/**
*
* #param length
* The length
*/
public void setLength(Integer length) {
this.length = length;
}
/**
*
* #return
* The breadth
*/
public Integer getBreadth() {
return breadth;
}
/**
*
* #param breadth
* The breadth
*/
public void setBreadth(Integer breadth) {
this.breadth = breadth;
}
}
Attributes:
public class AttributeList {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("productId")
#Expose
private Integer productId;
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The productId
*/
public Integer getProductId() {
return productId;
}
/**
*
* #param productId
* The productId
*/
public void setProductId(Integer productId) {
this.productId = productId;
}
}
The main class:
public class Example {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("promotedProducts")
#Expose
private List<PromotedProduct> promotedProducts = new ArrayList<PromotedProduct>();
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The promotedProducts
*/
public List<PromotedProduct> getPromotedProducts() {
return promotedProducts;
}
/**
*
* #param promotedProducts
* The promotedProducts
*/
public void setPromotedProducts(List<PromotedProduct> promotedProducts) {
this.promotedProducts = promotedProducts;
}
}
And the last Product:
public class Product {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("reviewList")
#Expose
private List<Object> reviewList = new ArrayList<Object>();
#SerializedName("productDetail")
#Expose
private ProductDetail productDetail;
#SerializedName("attributeList")
#Expose
private List<AttributeList> attributeList = new ArrayList<AttributeList>();
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The reviewList
*/
public List<Object> getReviewList() {
return reviewList;
}
/**
*
* #param reviewList
* The reviewList
*/
public void setReviewList(List<Object> reviewList) {
this.reviewList = reviewList;
}
/**
*
* #return
* The productDetail
*/
public ProductDetail getProductDetail() {
return productDetail;
}
/**
*
* #param productDetail
* The productDetail
*/
public void setProductDetail(ProductDetail productDetail) {
this.productDetail = productDetail;
}
/**
*
* #return
* The attributeList
*/
public List<AttributeList> getAttributeList() {
return attributeList;
}
/**
*
* #param attributeList
* The attributeList
*/
public void setAttributeList(List<AttributeList> attributeList) {
this.attributeList = attributeList;
}
}
Of course you need to polish it a bit. I just copy-pasted the generated files. You can change your main class there from "Example" to whatever you may like plus remove some stuff you do not like.
Related
I migrated from GreenDao3 to ObjectBox, and my project is't build.
I get errors like this
../app/build/generated/source/kapt/indexDebug/com/aff/index/main/boxdb/AliasDao.java
Error:(53, 29) error: cannot find symbol method getContentId()
This was my Alias class in GD3:
import org.greenrobot.greendao.annotation.*;
import com.aff.index.main.db.DaoSession;
import org.greenrobot.greendao.DaoException;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table "ALIAS".
*/
#Entity(active = true)
public class Alias {
#Id
private Long id;
private String name;
private String email;
private Long aliasContentId;
/** Used to resolve relations */
#Generated
private transient DaoSession daoSession;
/** Used for active entity operations. */
#Generated
private transient AliasDao myDao;
#ToOne(joinProperty = "aliasContentId")
private Content content;
#Generated
private transient Long content__resolvedKey;
#Generated
public Alias() {
}
public Alias(Long id) {
this.id = id;
}
#Generated
public Alias(Long id, String name, String email, Long aliasContentId) {
this.id = id;
this.name = name;
this.email = email;
this.aliasContentId = aliasContentId;
}
/** called by internal mechanisms, do not call yourself. */
#Generated
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getAliasDao() : null;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getAliasContentId() {
return aliasContentId;
}
public void setAliasContentId(Long aliasContentId) {
this.aliasContentId = aliasContentId;
}
/** To-one relationship, resolved on first access. */
#Generated
public Content getContent() {
Long __key = this.aliasContentId;
if (content__resolvedKey == null || !content__resolvedKey.equals(__key)) {
__throwIfDetached();
ContentDao targetDao = daoSession.getContentDao();
Content contentNew = targetDao.load(__key);
synchronized (this) {
content = contentNew;
content__resolvedKey = __key;
}
}
return content;
}
#Generated
public void setContent(Content content) {
synchronized (this) {
this.content = content;
aliasContentId = content == null ? null : content.getId();
content__resolvedKey = aliasContentId;
}
}
/**
* Convenient call for {#link org.greenrobot.greendao.AbstractDao#delete(Object)}.
* Entity must attached to an entity context.
*/
#Generated
public void delete() {
__throwIfDetached();
myDao.delete(this);
}
/**
* Convenient call for {#link org.greenrobot.greendao.AbstractDao#update(Object)}.
* Entity must attached to an entity context.
*/
#Generated
public void update() {
__throwIfDetached();
myDao.update(this);
}
/**
* Convenient call for {#link org.greenrobot.greendao.AbstractDao#refresh(Object)}.
* Entity must attached to an entity context.
*/
#Generated
public void refresh() {
__throwIfDetached();
myDao.refresh(this);
}
#Generated
private void __throwIfDetached() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
}
}
This is the ObjectBox Alias class:
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table "ALIAS".
*/
#Entity()
public class Alias {
#Id
private long id;
private String name;
private String email;
private long aliasContentId;
private ToOne<Content> content;
public Alias() {
}
public Alias(long id) {
this.id = id;
}
public Alias(long id, String name, String email, long aliasContentId, ToOne<Content> content) {
this.id = id;
this.name = name;
this.email = email;
this.aliasContentId = aliasContentId;
this.content = content;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getAliasContentId() {
return aliasContentId;
}
public void setAliasContentId(long aliasContentId) {
this.aliasContentId = aliasContentId;
}
public ToOne<Content> getContent() {
return content;
}
public void setContent(ToOne<Content> content) {
this.content = content;
}
}
And this is the DAO was generated by ObjectBox
// THIS CODE IS GENERATED BY objectbox, DO NOT EDIT.
/**
* DAO for table "Alias".
*/
public class AliasDao extends AbstractDao<Alias, Long> {
public static final String TABLENAME = "Alias";
/**
* Properties of the Alias box.
*/
private static io.objectbox.EntityInfo BOX_PROPERTIES = new Alias_();
/**
* Properties of entity Alias.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = Alias_.id;
public final static Property Name = Alias_.name;
public final static Property Email = Alias_.email;
public final static Property AliasContentId = Alias_.aliasContentId;
public final static Property ContentId = Alias_.contentId;
}
private Query<Alias> content_AliasesQuery;
public AliasDao(Box<Alias> box, IdentityScopeLong<Alias> identityScope) {
super(box, BOX_PROPERTIES, identityScope);
}
public AliasDao(DaoSession daoSession, Box<Alias> box, IdentityScopeLong<Alias> identityScope) {
super(daoSession, box, BOX_PROPERTIES, identityScope);
}
#Override
public void readEntity(Alias from, Alias to) {
to.setId(from.getId());
to.setName(from.getName());
to.setEmail(from.getEmail());
to.setAliasContentId(from.getAliasContentId());
to.setContentId(from.getContentId());
}
#Override
public Long getKey(Alias entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
#Override
protected final boolean isEntityUpdateable() {
return true;
}
}
This was the Alias Entity at GD3 Daogenerator
Entity alias = schema.addEntity(ENTITY_ALIAS);
alias.addIdProperty();
alias.addStringProperty(PROPERTY_NAME);
alias.addStringProperty(PROPERTY_EMAIL);
Property aliasContentId = alias.addLongProperty("aliasContentId").getProperty();
alias.addToOne(content, aliasContentId);
ToMany contentToAlias = content.addToMany(alias, aliasContentId);
contentToAlias.setName(ALIASES);
I can't find out why Object Box generates getContentId() into the DAO, or how can I resolve it.
contentId is the default name of the property storing the ID of the to-one relation content. Thus, if you want to use aliasContentId instead, you need to specify the name using #TargetIdProperty:
#TargetIdProperty("aliasContentId")
private ToOne<Content> content;
This question already has answers here:
Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?
(2 answers)
Closed 6 years ago.
good evening everyone, Ive been searching for a solution to an error android studio's log is sending using RecyclerView to show a JSON "product" list with retrofit.
I have already read the questions related to this error but im not able to find the right answer to my needs.
Android: RecyclerView: No adapter attached; skipping layout
No adapter attached; skipping layout recyclerview error
recyclerview No adapter attached; skipping layout
No adapter attached; skipping layout onCreateView()
This is de error log showed by android studio
RecyclerView: No adapter attached; skipping layout
RecyclerView: No adapter attached; skipping layout
Surface: getSlotFromBufferLocked: unknown buffer: 0xa3d9a700
OpenGLRenderer: endAllStagingAnimators on 0xa2b6bb00 (RippleDrawable) with handle 0xa200a310
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
For this proyect are been used this Classes and Layout files
"Producto" Class
public class Producto {
#SerializedName("id")
#Expose
private int id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("status")
#Expose
private String status;
#SerializedName("price")
#Expose
private String price;
#SerializedName("regular_price")
#Expose
private String regularPrice;
#SerializedName("sale_price")
#Expose
private String salePrice;
#SerializedName("price_html")
#Expose
private String priceHtml;
#SerializedName("on_sale")
#Expose
private boolean onSale;
#SerializedName("total_sales")
#Expose
private int totalSales;
#SerializedName("purchase_note")
#Expose
private String purchaseNote;
#SerializedName("categories")
#Expose
private List<Category> categories;
#SerializedName("menu_order")
#Expose
private int menuOrder;
/**
*
* #return
* The id
*/
public int getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The status
*/
public String getStatus() {
return status;
}
/**
*
* #param status
* The status
*/
public void setStatus(String status) {
this.status = status;
}
/**
*
* #return
* The price
*/
public String getPrice() {
return price;
}
/**
*
* #param price
* The price
*/
public void setPrice(String price) {
this.price = price;
}
/**
*
* #return
* The regularPrice
*/
public String getRegularPrice() {
return regularPrice;
}
/**
*
* #param regularPrice
* The regular_price
*/
public void setRegularPrice(String regularPrice) {
this.regularPrice = regularPrice;
}
/**
*
* #return
* The salePrice
*/
public String getSalePrice() {
return salePrice;
}
/**
*
* #param salePrice
* The sale_price
*/
public void setSalePrice(String salePrice) {
this.salePrice = salePrice;
}
/**
*
* #return
* The priceHtml
*/
public String getPriceHtml() {
return priceHtml;
}
/**
*
* #param priceHtml
* The price_html
*/
public void setPriceHtml(String priceHtml) {
this.priceHtml = priceHtml;
}
/**
*
* #return
* The onSale
*/
public boolean isOnSale() {
return onSale;
}
/**
*
* #param onSale
* The on_sale
*/
public void setOnSale(boolean onSale) {
this.onSale = onSale;
}
/**
*
* #return
* The totalSales
*/
public int getTotalSales() {
return totalSales;
}
/**
*
* #param totalSales
* The total_sales
*/
public void setTotalSales(int totalSales) {
this.totalSales = totalSales;
}
/**
*
* #return
* The purchaseNote
*/
public String getPurchaseNote() {
return purchaseNote;
}
/**
*
* #param purchaseNote
* The purchase_note
*/
public void setPurchaseNote(String purchaseNote) {
this.purchaseNote = purchaseNote;
}
/**
*
* #return
* The categories
*/
public List<Category> getCategories() {
return categories;
}
/**
*
* #param categories
* The categories
*/
public void setCategories(List<Category> categories) {
this.categories = categories;
}
/**
*
* #return
* The menuOrder
*/
public int getMenuOrder() {
return menuOrder;
}
/**
*
* #param menuOrder
* The menu_order
*/
public void setMenuOrder(int menuOrder) {
this.menuOrder = menuOrder;
}
}
"Category" Class (which matches with the private List<Category> categories; property)
public class Category {
#SerializedName("id")
#Expose
private int id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
/**
*
* #return
* The id
*/
public int getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The slug
*/
public String getSlug() {
return slug;
}
/**
*
* #param slug
* The slug
*/
public void setSlug(String slug) {
this.slug = slug;
}
}
Both Containanied as Arrays in this class called "JSONproducts"
public class JSONproducts {
private Producto[] products;
private Category[] categories;
public Producto[] getProducts(){
return products;
}
public Category[] getCategories(){
return categories;
}
}
Then The Request Interface called "LecturaProductos"
public interface LecturaProductos {
#GET("Products")
Call<JSONproducts> ListarProductos();
}
The data Adapter for the Recycler View called "Adaptador"
public class Adaptador extends RecyclerView.Adapter<Adaptador.ViewHolder> {
private ArrayList<Producto> productos;
private ArrayList<Category> categoria;
public Adaptador(ArrayList<Producto> productos, ArrayList<Category> categoria){
this.productos = productos;
this.categoria = categoria;
}
#Override
public Adaptador.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_view, parent, false );
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(Adaptador.ViewHolder holder, int position) {
holder.nom_pro_tv.setText(productos.get(position).getName());
holder.id_pro_tv.setText(productos.get(position).getId());
holder.cat_pro.setText(categoria.get(position).getName());
}
#Override
public int getItemCount() {
return productos.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView nom_pro_tv, id_pro_tv, cat_pro;
public ViewHolder(View itemView) {
super(itemView);
nom_pro_tv = (TextView)itemView.findViewById(R.id.nom_pro_tv);
id_pro_tv = (TextView)itemView.findViewById(R.id.id_pro_tv);
cat_pro = (TextView)itemView.findViewById(R.id.cat_pro_tv);
}
}
}
And the Activity Class "ListaProductos"
public class ListaProductos extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<Producto> product;
private ArrayList<Category> category;
private Adaptador adaptador;
public static final String BASE_URL= "https://mydomain.com.mx/wp-json/wc/v1/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_productos);
showView();
}
private void showView(){
recyclerView = (RecyclerView)findViewById(R.id.prod_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
cargarJSON();
}
private void cargarJSON(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
final LecturaProductos producto = retrofit.create(LecturaProductos.class);
Call<JSONproducts> productoCall = producto.ListarProductos();
productoCall.enqueue(new Callback<JSONproducts>() {
#Override
public void onResponse(Call<JSONproducts> call, Response<JSONproducts> response) {
JSONproducts jsonproducts = response.body();
product = new ArrayList<>(Arrays.asList(jsonproducts.getProducts()));
category = new ArrayList<>(Arrays.asList(jsonproducts.getCategories()));
adaptador = new Adaptador(product, category);
recyclerView.setAdapter(adaptador);
}
#Override
public void onFailure(Call<JSONproducts> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
}
And the Layout XML files that are been used
RecyclerView Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_lista_productos"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mx.com.corpcap.elrollorepartidor.ListaProductos">
<android.support.v7.widget.RecyclerView
android:id="#+id/prod_recycler_view"
android:layout_height="match_parent"
android:layout_width="match_parent"/></LinearLayout>
CardView Layout for the product list
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/nom_pro_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<TextView
android:id="#+id/id_pro_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/cat_pro_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
Everything complies great and launches the app without an issue but when the information is tried to be accessed it sends the log messages quoted in the beginning of this question.
Thanks a Lot
A RecyclerView is not much use on it's own without an adapter providing the data it must display. So when a RecyclerView is initialized and placed in the layout but .setAdapter has not yet been called, the problem you're experiencing occurs. How about you take an empty list and use that to initialize the adapter and set it to your RecyclerView before you even send the network request. When you make the network request and get a response, simply clear the old values in the list, add new values and notify your adapter that the data in the list has changed. This should avoid the skipping layout problem, Alex.
Something like this:
private ArrayList<YourObjectClass> listOfYourObjects = new ArrayList<>();
.
.
.
SomeAdapter yourAdapter = new SomeAdapter(listOfYourObjects , context);
yourRecyclerView.setAdapter(yourAdapter);
.
.
.
onResponse:
list.clear();
//Let the adapter know the list is empty now
yourAdapter.notifyDataSetChanged();
//Fill in your list with values from server using a for/while loop etc.
//Again notify your adapter that the list has changed:
yourAdapter.notifyDataSetChanged();
Hope that helps.
I've one class, in which array list is there. How to send it through intent. following i did for my class
public class MakeOrder implements Parcelable {
#SerializedName("refno")
#Expose
private String refno;
#SerializedName("ddesc")
#Expose
private String ddesc;
#SerializedName("free")
#Expose
private String free;
#SerializedName("fgift")
#Expose
private String fgift;
#SerializedName("sgift")
#Expose
private String sgift;
#SerializedName("sandage")
#Expose
private SandageResponse sandage;
#SerializedName("inst")
#Expose
private String inst;
#SerializedName("items")
#Expose
private List<Item> items = new ArrayList<Item>();
#SerializedName("discount")
#Expose
private String discount;
#SerializedName("coupon")
#Expose
private Coupon coupon;
#SerializedName("delivery")
#Expose
private String delivery;
#SerializedName("user")
#Expose
private User user;
#SerializedName("otype")
#Expose
private String otype;
#SerializedName("ptype")
#Expose
private String ptype;
#SerializedName("app_id")
#Expose
private String appId;
#SerializedName("app_key")
#Expose
private String appKey;
#SerializedName("request")
#Expose
private String request;
#SerializedName("tablename")
#Expose
private String tablename;
#SerializedName("staff")
#Expose
private String staff;
public String getTablename() {
return tablename;
}
public void setTablename(String tablename) {
this.tablename = tablename;
}
public String getStaff() {
return staff;
}
public void setStaff(String staff) {
this.staff = staff;
}
public String getRefno() {
return refno;
}
public void setRefno(String refno) {
this.refno = refno;
}
public String getDdesc() {
return ddesc;
}
public void setDdesc(String ddesc) {
this.ddesc = ddesc;
}
public String getFree() {
return free;
}
public void setFree(String free) {
this.free = free;
}
public String getFgift() {
return fgift;
}
public void setFgift(String fgift) {
this.fgift = fgift;
}
public String getSgift() {
return sgift;
}
public void setSgift(String sgift) {
this.sgift = sgift;
}
public SandageResponse getSandage() {
return sandage;
}
public void setSandage(SandageResponse sandage) {
this.sandage = sandage;
}
public String getInst() {
return inst;
}
public void setInst(String inst) {
this.inst = inst;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public Coupon getCoupon() {
return coupon;
}
public void setCoupon(Coupon coupon) {
this.coupon = coupon;
}
public String getDelivery() {
return delivery;
}
public void setDelivery(String delivery) {
this.delivery = delivery;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getOtype() {
return otype;
}
public void setOtype(String otype) {
this.otype = otype;
}
public String getPtype() {
return ptype;
}
public void setPtype(String ptype) {
this.ptype = ptype;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getAppKey() {
return appKey;
}
public void setAppKey(String appKey) {
this.appKey = appKey;
}
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.refno);
dest.writeString(this.ddesc);
dest.writeString(this.free);
dest.writeString(this.fgift);
dest.writeString(this.sgift);
dest.writeParcelable(this.sandage, flags);
dest.writeString(this.inst);
dest.writeTypedList(this.items);
dest.writeString(this.discount);
dest.writeParcelable(this.coupon, flags);
dest.writeString(this.delivery);
dest.writeParcelable(this.user, flags);
dest.writeString(this.otype);
dest.writeString(this.ptype);
dest.writeString(this.appId);
dest.writeString(this.appKey);
dest.writeString(this.request);
dest.writeString(this.tablename);
dest.writeString(this.staff);
}
public MakeOrder() {
}
protected MakeOrder(Parcel in) {
this.refno = in.readString();
this.ddesc = in.readString();
this.free = in.readString();
this.fgift = in.readString();
this.sgift = in.readString();
this.sandage = in.readParcelable(SandageResponse.class.getClassLoader());
this.inst = in.readString();
this.items = in.createTypedArrayList(Item.CREATOR);
this.discount = in.readString();
this.coupon = in.readParcelable(Coupon.class.getClassLoader());
this.delivery = in.readString();
this.user = in.readParcelable(User.class.getClassLoader());
this.otype = in.readString();
this.ptype = in.readString();
this.appId = in.readString();
this.appKey = in.readString();
this.request = in.readString();
this.tablename = in.readString();
this.staff = in.readString();
}
public static final Parcelable.Creator<MakeOrder> CREATOR = new Parcelable.Creator<MakeOrder>() {
#Override
public MakeOrder createFromParcel(Parcel source) {
return new MakeOrder(source);
}
#Override
public MakeOrder[] newArray(int size) {
return new MakeOrder[size];
}
};
}
Please take a look of updated one
I'm getting error like unable to marshal value
I made all class Parcelable. how to send its object through Intent
Thanks in Advance
Logcat is like
java.lang.RuntimeException: Parcel: unable to marshal value Models.PlaceOrder.Sub#41e10f80
at android.os.Parcel.writeValue(Parcel.java:1235)
at android.os.Parcel.writeList(Parcel.java:622)
at Models.PlaceOrder.Item.writeToParcel(Item.java:90)
at android.os.Parcel.writeTypedList(Parcel.java:1017)
at Models.PlaceOrder.MakeOrder.writeToParcel(MakeOrder.java:246)
at android.os.Parcel.writeParcelable(Parcel.java:1254)
at android.os.Parcel.writeValue(Parcel.java:1173)
at android.os.Parcel.writeMapInternal(Parcel.java:591)
at android.os.Bundle.writeToParcel(Bundle.java:1627)
at android.os.Parcel.writeBundle(Parcel.java:605)
at android.content.Intent.writeToParcel(Intent.java:6866)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1897)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1418)
at android.app.Activity.internalStartActivityForResult(Activity.java:3427)
at android.app.Activity.access$200(Activity.java:660)
at android.app.Activity$2.onStartActivity(Activity.java:3417)
at android.app.Activity.startActivityForBusiness(Activity.java:5441)
at android.app.Activity.startActivityForResult(Activity.java:3413)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
at android.app.Activity.startActivityForResult(Activity.java:3367)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:871)
at android.app.Activity.startActivity(Activity.java:3644)
at android.app.Activity.startActivity(Activity.java:3612)
Items.java where getting Exception
public class Item implements Parcelable {
#SerializedName("itemid")
#Expose
private String itemid;
#SerializedName("qty")
#Expose
private String qty;
#SerializedName("sub")
#Expose
private List<Sub> sub = new ArrayList<Sub>();
/**
*
* #return
* The itemid
*/
public String getItemid() {
return itemid;
}
/**
*
* #param itemid
* The itemid
*/
public void setItemid(String itemid) {
this.itemid = itemid;
}
/**
*
* #return
* The qty
*/
public String getQty() {
return qty;
}
/**
*
* #param qty
* The qty
*/
public void setQty(String qty) {
this.qty = qty;
}
/**
*
* #return
* The sub
*/
public List<Sub> getSub() {
return sub;
}
/**
*
* #param sub
* The sub
*/
public void setSub(List<Sub> sub) {
this.sub = sub;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.itemid);
dest.writeString(this.qty);
dest.writeList(this.sub);
}
public Item() {
}
protected Item(Parcel in) {
this.itemid = in.readString();
this.qty = in.readString();
this.sub = new ArrayList<Sub>();
in.readList(this.sub, Sub.class.getClassLoader());
}
public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() {
#Override
public Item createFromParcel(Parcel source) {
return new Item(source);
}
#Override
public Item[] newArray(int size) {
return new Item[size];
}
};
}
You need to implement Parcelable also in the Item and Coupon objects.
Then when you add and read the list in you MakeOrder class:
#Override
public void writeToParcel(Parcel dest, int flags) {
...
// to write the Item list
dest.writeList(items);
// to write Coupon object
dest.writeParcelable(coupon, falgs);
}
BTW, your constructor is empty
private MakeOrder(Parcel in) {
...
// to read the Item list
items = new ArrayList<Item>();
in.readList(items, Item.CREATOR);
// to read Coupon object
in.readParcelable(Coupon.CREATOR);
}
This link could help you:
How to make a class with nested objects Parcelable
And this is the Parcelable documentation:
https://developer.android.com/reference/android/os/Parcel.html
EDIT:
The where more Percel problem added to the question.
Final solution in chat: https://chat.stackoverflow.com/rooms/123710/discussion-between-aman-singh-and-adalpari
You need to put in extras like this:
Intent intent-new Intent(this,YouActvity.class);
intent.putExtra("key",yourModel);
startActivity(intent);
In Activity to retrive:
YouModel yourModel = (YourModel) getIntent().getSerializableExtra("key");
Firstly, your Parcelable constructor is empty. If you leave it empty, then it won't work. You need to read fields from parcel the same order you wrote them in writeToParcel() method.
Then to write parcelable data to intent, putExtra() method of the intent. To extract data from intent, use getParcelableExtra() method of the intent
Try using this
intent.putParcelableArrayListExtra("value", orderList);
And in other Activity get it as:
List<String> orderList=this.getIntent().
getParcelableArrayListExtra("value");
Hope this helps
I'm trying to populate a layout of mine by looping through some requested JSON (I use Retrofit).
When I try to populate the layout manually (like below), it displays fine:
Post post1 = new Post("1", "1", "This is a message.");
But if I try to populate it with the requested JSON data, the layout doesn't get populated nor does it display on my screen. Only the layout with "This is a message." is displayed.
Here is the code within my onCreateView() for my fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) view.findViewById(R.id.listview_posts);
final ArrayList<Post> arrayOfUsers = new ArrayList<Post>();
// This works fine. It populates the layout as it should.
Post post1 = new Post("1", "1", "This is a message.");
arrayOfUsers.add(post1);
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.build();
final ApiEndpointInterface apiService = restAdapter.create(ApiEndpointInterface.class);
apiService.getJsonStuff(1, new Callback<PostData>() {
#Override
public void success(PostData postData, Response response) {
// This doesn't work either
Post post2 = new Post("1", "1", "This is a message2.");
arrayOfUsers.add(post2);
for (Post p : postData.data) {
// This does not work. The layout isn't populated nor does it display.
Post posty = new Post(p.getId(), p.getUserId(), p.getContent());
arrayOfUsers.add(posty);
// The JSON is being read correctly, since this prints out the right values.
Log.d("MESSAGE", p.getMessage());
}
}
#Override
public void failure(RetrofitError retrofitError) {
retrofitError.printStackTrace();
}
});
PostAdapter adapter = new PostAdapter(getActivity(), arrayOfUsers);
listView.setAdapter(adapter);
return view;
}
The callback:
void getJsonStuff(#Path("user_id") int userId, Callback<PostData> response);
Post model:
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Post {
#Expose
private String id;
#SerializedName("user_id")
#Expose
private String userId;
#Expose
private String content;
public Post(String id, String userId, String content) {
this.id = id;
this.userId = userId;
this.content = content;
}
/**
*
* #return
* The id
*/
public String getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* #return
* The userId
*/
public String getUserId() {
return userId;
}
/**
*
* #param userId
* The user_id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
*
* #return
* The content
*/
public String getContent() {
return content;
}
/**
*
* #param content
* The content
*/
public void setContent(String content) {
this.content= content;
}
}
PostData model:
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
public class PostData {
#Expose
public Boolean success;
#Expose
public List<Post> data = new ArrayList<Post>();
/**
*
* #return
* The success
*/
public Boolean getSuccess() {
return success;
}
/**
*
* #param success
* The success
*/
public void setSuccess(Boolean success) {
this.success = success;
}
/**
*
* #return
* The data
*/
public List<Post> getData() {
return data;
}
/**
*
* #param data
* The data
*/
public void setData(List<Post> data) {
this.data = data;
}
}
In the scenario that works for you -> you are doing the things sequentially: create the Post object - add it to the list - create the adapter based on the non-empty list - set the adapter on the list.
In the scenario that doesn't work, you are doing them asynchronously: create empty list - trigger request for data (but no data yet) - create adapter - set the adapter on the list - at some undetermined moment in the future data arrives. The problem is that in this case the adapter doesn't know that anything changed, so you need to notify it (at the end of your success callback):
adapter.notifyDataSetChanged()
Your getJsonStuff method should be declared something like...
getJsonStuff(int id, Callback<List<Post>> callback)
I'm trying to send an ArrayList of custom objects to the next activity but its not working for me. I've been all day trying to implement Parcelable with no luck at all. I've done my research here on SO but i'm still getting an error: Cannot convert Parceable[] to ArraList<Song> This is my code for parceling my object:
// Parcelling part
public Song(Parcel in){
this._id = in.readInt();
this.name = in.readString();
this.path = in.readString();
this.artistId = in.readInt();
this.albumId = in.readInt();
}
#Override
public int describeContents(){
return 0;
}
public static final Parcelable.Creator<Song> CREATOR = new Parcelable.Creator<Song>() {
public Song createFromParcel(Parcel in) {
return new Song(in);
}
public Song[] newArray(int size) {
return new Song[size];
}
};
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(_id);
dest.writeString(name);
dest.writeString(path);
dest.writeInt(artistId);
dest.writeInt(albumId);
}
In my first activity i just:
ArrayList<Song> songs = db.selectAllSongs();
playerActivity.putParcelableArrayListExtra("songs", songs);
And in my second activity i just:
ArrayList<Song> songs = getIntent().getParcelableArrayExtra("songs");
I don't know why im getting an error when i'm implementing Parceable. I need a little guiding. Thanks in advance.
I hope this will help for you. In this way i am using parcellable values
public class Channel implements Serializable, Parcelable {
/** */
private static final long serialVersionUID = 4861597073026532544L;
private String cid;
private String uniqueID;
private String name;
private String logo;
/**
* #return the cid
*/
public String getCid() {
return cid;
}
/**
* #param cid
* the cid to set
*/
public void setCid(String cid) {
this.cid = cid;
}
/**
* #return the uniqueID
*/
public String getUniqueID() {
return uniqueID;
}
/**
* #param uniqueID
* the uniqueID to set
*/
public void setUniqueID(String uniqueID) {
this.uniqueID = uniqueID;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the logo
*/
public String getLogo() {
return logo;
}
/**
* #param logo
* the logo to set
*/
public void setLogo(String logo) {
this.logo = logo;
}
public Channel(Parcel in) {
super();
readFromParcel(in);
}
public static final Parcelable.Creator<Channel> CREATOR = new Parcelable.Creator<Channel>() {
public Channel createFromParcel(Parcel in) {
return new Channel(in);
}
public Channel[] newArray(int size) {
return new Channel[size];
}
};
public void readFromParcel(Parcel in) {
String[] result = new String[23];
in.readStringArray(result);
this.cid = result[0];
this.uniqueID = result[1];
this.name = result[2];
this.logo = result[3];
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] { this.cid, this.uniqueID,
this.name, this.logo});
}}
And in Activity class
bundle.putParcelableArrayList("channel",
(ArrayList<Channel>) channels);
And in the second Activity screen get the bundle parcelable array like this
Bundle getBundle = this.getIntent().getExtras();
List<Channel> channelsList = getBundle.getParcelableArrayList("channel");
The method Intent.getParcelableArrayExtra() (link) returns an array of parcelable objects. You're assigning that to an ArrayList object, and the compiler is complaining because ArrayLists aren't arrays.
Try using getParcelableArrayListExtra() instead.