简体   繁体   English

RecyclerView Android不会显示Gson响应的任何结果

[英]RecyclerView Android does not show any result for Gson response

I am creating an application that fetches JSON data from the server and displays it in my recyclerView. 我正在创建一个从服务器获取JSON数据并将其显示在我的recyclerView中的应用程序。 I am successfully able to fetch JSON data but when I set it to recyclerView, it does not show anything over there. 我可以成功获取JSON数据,但是当我将其设置为recyclerView时,它不会显示任何内容。 In fact, there are no errors in the logcat. 实际上,logcat中没有错误。

  1. My JSON Data: 我的JSON数据:
       {
        "description": [
            {
                "title": "Product Details",
                "details": [
                    {
                        "key": "Item Code",
                        "value": "18NOTNIGHTBLK"
                    },
                    {
                        "key": "Colour",
                        "value": "Black"
                    },
                    {
                        "key": "Gender",
                        "value": "Men"
                    },
                    {
                        "key": "Product Type",
                        "value": "T-Shirts"
                    },
                    {
                        "key": "Occasion",
                        "value": "Casual"
                    },
                    {
                        "key": "Season",
                        "value": "SS18"
                    },
                    {
                        "key": "Material",
                        "value": "Cotton"
                    },
                    {
                        "key": "Pattern",
                        "value": "Printed"
                    },
                    {
                        "key": "Product Fit",
                        "value": "Regular"
                    },
                    {
                        "key": "Sleeve Length",
                        "value": "Short"
                    },
                    {
                        "key": "Neck Type",
                        "value": "Round Neck"
                    },
                    {
                        "key": "Care Instructions",
                        "value": "Machine Wash"
                    }
                ],
                "text": ""
            }
        ],
        "logo": {
            "url": "http://cdn4.gofynd.com/media/logo/brand/50x0/2110_767367ba75c34d569ea2a3ba27cc66aa.jpg",
            "action": {
                "url": "https://api.addsale.com/v0.1/product/by-brand/?brand_slug=437",
                "type": "brand"
            },
            "aspect_ratio": "1:1"
        },
        "images": [
            {
                "aspect_ratio": "16:25",
                "url": "http://cdn4.gofynd.com/media/pictures/tagged_items/270x0/437_18NOTNIGHTBLK/1_1528806531490.jpg"
            },
            {
                "aspect_ratio": "16:25",
                "url": "http://cdn4.gofynd.com/media/pictures/tagged_items/270x0/437_18NOTNIGHTBLK/2_1528806531490.jpg"
            },
            {
                "aspect_ratio": "16:25",
                "url": "http://cdn4.gofynd.com/media/pictures/tagged_items/270x0/437_18NOTNIGHTBLK/3_1528806531490.jpg"
            },
            {
                "aspect_ratio": "16:25",
                "url": "http://cdn4.gofynd.com/media/pictures/tagged_items/270x0/437_18NOTNIGHTBLK/4_1528806531490.jpg"
            },
            {
                "aspect_ratio": "16:25",
                "url": "http://cdn4.gofynd.com/media/pictures/tagged_items/270x0/437_18NOTNIGHTBLK/5_1528806531490.jpg"
            }
        ],
        "price_effective": "999",
        "sizes": [
            {
                "is_available": false,
                "value": "XS",
                "display": "XS",
                "article_id": "307_437_PUNK01_18NOTNIGHTBLK_XS"
            },
            {
                "is_available": true,
                "value": "S",
                "display": "S",
                "article_id": "307_437_PUNK01_18NOTNIGHTBLK_S"
            },
            {
                "is_available": false,
                "value": "M",
                "display": "M",
                "article_id": "307_437_PUNK01_18NOTNIGHTBLK_M"
            },
            {
                "is_available": true,
                "value": "L",
                "display": "L",
                "article_id": "307_437_PUNK01_18NOTNIGHTBLK_L"
            },
            {
                "is_available": true,
                "value": "XL",
                "display": "XL",
                "article_id": "307_437_PUNK01_18NOTNIGHTBLK_XL"
            },
            {
                "is_available": true,
                "value": "XXL",
                "display": "XXL",
                "article_id": "307_437_PUNK01_18NOTNIGHTBLK_XXL"
            },
            {
                "is_available": false,
                "value": "3XL",
                "display": "3XL",
                "article_id": "307_437_PUNK01_18NOTNIGHTBLK_3XL"
            }
        ],
        "brand": "PUNK",
        "size_chart": {
            "sizes": [
                {
                    "unit": "",
                    "display": "brand size",
                    "values": [
                        "S",
                        "M",
                        "L",
                        "XL",
                        "XXL",
                        "3XL"
                    ],
                    "priority": 0
                },
                {
                    "unit": "in",
                    "display": "chest",
                    "values": [
                        "38",
                        "40",
                        "42",
                        "44",
                        "46",
                        "48"
                    ],
                    "priority": 1
                },
                {
                    "unit": "in",
                    "display": "shoulder",
                    "values": [
                        "17",
                        "17.5",
                        "18",
                        "18.5",
                        "19",
                        "19.5"
                    ],
                    "priority": 2
                }
            ],
            "size_tip": "All measurements shown are of the garment."
        },
        "price_marked": "999",
        "share_url": "https://go.fyndi.ng/7D73ivPLGN",
        "product_name": "Black Printed T-Shirt",
        "discount": "",
        "is_in_stock": true,
        "product_url": "https://www.gofynd.com/punk-black-printed-t-shirt-575425-2c8ee2.html",
        "product_id": 575425,
        "slug": "punk-black-printed-t-shirt-575425-2c8ee2",
        "has_variant": true
    }
  1. Model Class: 型号类别:
    public class ProductDetailItem extends ProductDetailsGet {

        @Expose
        private ArrayList<ProductDetailItem> items = null;

        public ArrayList<ProductDetailItem> getItems() {
            return items;
        }

        public void setItems(ArrayList<ProductDetailItem> items) {
            this.items = items;
        }

    }
  1. Another Model Class 另一个模型类
    public class ProductDetailsGet extends Description{

        /*@SerializedName("description")
        @Expose
        private ArrayList<Description> description = null;*/

        @SerializedName("price_effective")
        @Expose
        private String priceEffective;
        @SerializedName("sizes")
        @Expose
        private List<Size> sizes = null;
        @SerializedName("brand")
        @Expose
        private String brand;
        @SerializedName("price_marked")
        @Expose
        private String priceMarked;
        @SerializedName("share_url")
        @Expose
        private String shareUrl;
        @SerializedName("product_name")
        @Expose
        private String productName;
        @SerializedName("discount")
        @Expose
        private String discount;
        @SerializedName("is_in_stock")
        @Expose
        private String isInStock;
        @SerializedName("product_url")
        @Expose
        private String productUrl;
        @SerializedName("product_id")
        @Expose
        private Integer productId;
        @SerializedName("slug")
        @Expose
        private String slug;
        @SerializedName("has_variant")
        @Expose
        private Boolean hasVariant;

       /* public ArrayList<Description> getDescription() {
            return description;
        }

        public void setDescription(ArrayList<Description> description) {
            this.description = description;
        }*/


        public String getPriceEffective() {
            return String.valueOf(priceEffective);
        }


        public List<Size> getSizes() {
            return sizes;
        }

        public void setSizes(List<Size> sizes) {
            this.sizes = sizes;
        }

        public String getBrand() {
            return brand;
        }


        public String getPriceMarked() {
            return priceMarked;
        }


        public String getShareUrl() {
            return shareUrl;
        }

        public void setShareUrl(String shareUrl) {
            this.shareUrl = shareUrl;
        }

        public String getProductName() {
            return productName;
        }


        public String getDiscount() {
            return discount;
        }

        public void setDiscount(String discount) {
            this.discount = discount;
        }

        public String getIsInStock() {
            return isInStock;
        }

        public void setIsInStock(String isInStock) {
            this.isInStock = isInStock;
        }

        public String getProductUrl() {
            return productUrl;
        }

        public void setProductUrl(String productUrl) {
            this.productUrl = productUrl;
        }

        public Integer getProductId() {
            return productId;
        }

        public void setProductId(Integer productId) {
            this.productId = productId;
        }

        public String getSlug() {
            return slug;
        }

        public void setSlug(String slug) {
            this.slug = slug;
        }

        public Boolean getHasVariant() {
            return hasVariant;
        }

        public void setHasVariant(Boolean hasVariant) {
            this.hasVariant = hasVariant;
        }
    }
  1. Adapter Class: 适配器类别:
    public class ProductDetailAdapter extends RecyclerView.Adapter<ProductDetailAdapter.MyViewHolder> {

        Context context;
        ArrayList<ProductDetailItem> items;
        ProductDetailItem item;

        public ProductDetailAdapter(Context context, ProductDetailItem items) {
            this.context = context;
            this.item = items;
        }


        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.data_product, parent, false);

            return new MyViewHolder(view);
        }
        @Override
        public void onBindViewHolder(@NonNull ProductDetailAdapter.MyViewHolder holder, int position) {
            item = items.get(position);
            holder.item_code.setText(item.getTitle());
            holder.colour.setText(item.getValue());
            holder.gender.setText(item.getKey());
            holder.producttype.setText(item.getKey());
            holder.occasion.setText(item.getKey());
            holder.season.setText(item.getKey());
            holder.material.setText(item.getValue());
            holder.price.setText((CharSequence) item.getPriceEffective());
            holder.size_available.setText(item.size.getValue());
            holder.brand.setText(item.getBrand());
            holder.product_name_new.setText( item.getProductName());
            holder.discount_product.setText(item.getDiscount());
            holder.is_instock.setText(item.getIsInStock());
        }


        @Override
        public int getItemCount() {
            //return items.size();
            return null != items ? items.size() : 0;

        }

        public class MyViewHolder extends RecyclerView.ViewHolder {
            public TextView item_code,colour,gender,producttype,occasion,season,material,price,size_available,brand,product_name_new,
                    discount_product,is_instock;

            public MyViewHolder(View view) {
                super(view);
                item_code = (TextView) view.findViewById(R.id.item_code);
                colour = view.findViewById(R.id.colour);
                gender = view.findViewById(R.id.gender);
                producttype = view.findViewById(R.id.producttype);
                occasion = view.findViewById(R.id.occasion);
                season = (TextView) view.findViewById(R.id.season);
                material = view.findViewById(R.id.material);
                price = view.findViewById(R.id.price);
                size_available = view.findViewById(R.id.size_available);
                brand = view.findViewById(R.id.brand);
                product_name_new = (TextView) view.findViewById(R.id.product_name_new);
                discount_product = view.findViewById(R.id.discount_product);
                is_instock = view.findViewById(R.id.is_instock);
            }
        }
    }
  1. Activity Class: 活动类别:
    public class ProductDetailsActivity extends AppCompatActivity {
    TextView proid;
        OkHttpClient okHttpClient;
        FyndJsonApi fyndJsonApi;
        RecyclerView recyclerdetails;
        ArrayList<ProductDetailItem> item_details;
        ProgressDialog progressDialog;
        String data;
        ProductDetailItem productDetailItem;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_product_details);
            proid = findViewById(R.id.pro_id);
            recyclerdetails = findViewById(R.id.recyclerdetails);
            recyclerdetails.setLayoutManager(new LinearLayoutManager(this));
            recyclerdetails.setAdapter(new ProductDetailAdapter(ProductDetailsActivity.this, productDetailItem));
            Intent intent = this.getIntent();
            data = intent.getStringExtra("product-id");
            proid.setText(data);

            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


            okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new Interceptor() {
                        @Override
                        public okhttp3.Response intercept(Chain chain) throws IOException {
                            Request originalRequest = chain.request();

                            Request newRequest = originalRequest.newBuilder()
                                    .build();

                            return chain.proceed(newRequest);
                        }
                    })
                    .addInterceptor(loggingInterceptor)
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://api.addsale.com/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .client(okHttpClient)
                    .build();
            fyndJsonApi = retrofit.create(FyndJsonApi.class);

            ProductDetailsTask productDetailsGet = new ProductDetailsTask();
            productDetailsGet.execute("");

        }

        class ProductDetailsTask extends AsyncTask<String,String,String>
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog = new ProgressDialog(ProductDetailsActivity.this);
                progressDialog.setMessage("Loading Data.. Please Wait..");
                progressDialog.setCancelable(false);
                progressDialog.show();
            }

            @Override
            protected void onPostExecute(String s) {
                progressDialog.dismiss();
                super.onPostExecute(s);

            }

            @Override
            protected String doInBackground(String... strings) {
                Call<JsonObject> call = fyndJsonApi.getProductDetails("/affiliate/v0.1/product/",data);

                call.enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject>call, Response<JsonObject> response) {
                        JsonObject response1 = response.body();
                        productDetailItem = new Gson().fromJson(String.valueOf(response1), new TypeToken<ProductDetailItem>(){}.getType());
                        item_details = productDetailItem.getItems();
                        Toast.makeText(ProductDetailsActivity.this, "Success Connnection to API", Toast.LENGTH_LONG).show();
                        recyclerdetails.setItemAnimator(new DefaultItemAnimator());
                        recyclerdetails.setAdapter(new ProductDetailAdapter(getApplicationContext(),productDetailItem));
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        Log.e("Error",t.getMessage());
                        Toast.makeText(ProductDetailsActivity.this, "Failure connection to API", Toast.LENGTH_LONG).show();
                    }
                });
                return null;
            }
        }

    }
  1. JSON Interface: JSON接口:
    @GET("{relativeURL}")
        Call<JsonObject> getProductDetails(
                @Path(value = "relativeURL", encoded = true) String relativeUrl,
                @Query("product_id") String queryText);

I have not mentioned any layout files cause they might not be the reason. 我没有提到任何布局文件,因为它们可能不是原因。

Thank you 谢谢

You need to do below changes : 您需要进行以下更改:

ProductDetailAdapter ProductDetailAdapter

public ProductDetailAdapter(Context context, List<ProductDetailItem> items) {
  this.context = context;
  this.items = items;
}

ProductDetailsActivity 产品详细信息活动

ProductDetailAdapter mAdapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   ......
   mAdapter = new 
   ProductDetailAdapter(ProductDetailsActivity.this, item_details)
   recyclerdetails.setAdapter(mAdapter);
   .......   
}

ProductDetailsTask 产品详细信息任务

@Override
public void onResponse(Call<JsonObject>call, Response<JsonObject> response) {
     JsonObject response1 = response.body();
     productDetailItem = new Gson().fromJson(String.valueOf(response1), new TypeToken<ProductDetailItem>(){}.getType());
     item_details.clear();
     item_details.addAll(productDetailItem.getItems());
     mAdapter.notifyDataSetChanged();

}

Try setting the items on the adapter after you initiate it, like: 启动适配器后,尝试在适配器上设置项目,例如:

recyclerdetails.setItemAnimator(new DefaultItemAnimator());
ProductDetailAdapter adapter = new ProductDetailAdapter(getApplicationContext(),productDetailItem)
recyclerdetails.setAdapter();
ArrayList array = new ArrayList();
array.add(productDetailItem.getItems())
adapter.setItems(array);
adapter.notifyDataSetChanged()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM