翻新中未获取服务器数据

时间:2018-09-17 16:29:51

标签: android retrofit retrofit2

我想通过使用retrofit上的RecyclerView库从服务器中获取一些数据,但是该数据未显示在RecycleView上。我读了很多答案,但还没有解决,所以请先解决我的问题,谢谢。

下面是我的JSON数据

{
"item": [
    {
        "Item_Id": "1",
        "Item_Name": "Item Name 1",
        "Item_Description": "Item Name 1 Description",
        "Item_Price": "330.00",
        "Discount": "10",
        "Item_Image": "http://192.168.1.5/easyshop/Items_Image/xyz.jpg",
        "First_Name": "abc",
        "Last_Name": "xyz",
        "Mobile": "**********"
    },
    {
        "Item_Id": "2",
        "Item_Name": "Item Name 2",
        "Item_Description": "Item Name 2 Description",
        "Item_Price": "40.00",
        "Discount": "30",
        "Item_Image": "http://192.168.1.5/easyshop/Items_Image/xyz1.jpg",
        "First_Name": "def",
        "Last_Name": "uvw",
        "Mobile": "**********"
    }
  ]
 }

我使用了基础URL,GSON和改造对象的API客户端类

 public class ApiClient {

public static final String BASE_URL = "http://192.168.1.5/easyshop/";
private static Retrofit retrofit = null;

public static Retrofit getClient() {

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(100, TimeUnit.SECONDS)
            .readTimeout(100,TimeUnit.SECONDS)
            .build();

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }
    return retrofit;
  }
}

界面

 public interface APIService {
 @FormUrlEncoded
 @POST("GetItem.php")
 Call<ItemArray> getItem(@Field("Retailer_Id")int Retailer_Id);
}

当我将JSON数据放入www.jsonschema2pojo.org时,它会生成两个文件,如下所示

public class ItemArray {
  @SerializedName("item")
  @Expose
  private List<ItemList> item = null;

  public List<ItemList> getItem() {
      return item;
  }

 public void setItem(List<ItemList> item) {
      this.item = item;
   }
 }

getter设置程序类

 public class ItemList {
@SerializedName("Item_Id")
@Expose
private String itemId;
@SerializedName("Item_Name")
@Expose
private String itemName;
@SerializedName("Item_Description")
@Expose
private String itemDescription;
@SerializedName("Item_Price")
@Expose
private String itemPrice;
@SerializedName("Discount")
@Expose
private String discount;
@SerializedName("Item_Image")
@Expose
private String itemImage;
@SerializedName("First_Name")
@Expose
private String firstName;
@SerializedName("Last_Name")
@Expose
private String lastName;
@SerializedName("Mobile")
@Expose
private String mobile;

public String getItemId() {
    return itemId;
}

public void setItemId(String itemId) {
    this.itemId = itemId;
}

public String getItemName() {
    return itemName;
}

public void setItemName(String itemName) {
    this.itemName = itemName;
}

public String getItemDescription() {
    return itemDescription;
}

public void setItemDescription(String itemDescription) { this.itemDescription = itemDescription; }

public String getItemPrice() {
    return itemPrice;
}

public void setItemPrice(String itemPrice) {
    this.itemPrice = itemPrice;
}

public String getDiscount() {
    return discount;
}

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

public String getItemImage() {
    return itemImage;
}

public void setItemImage(String itemImage) {
    this.itemImage = itemImage;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getMobile() {
    return mobile;
}

public void setMobile(String mobile) {
    this.mobile = mobile;
  }
}

适配器类

public class Item_Card_Adapter  extends RecyclerView.Adapter<Item_Card_Adapter.ViewHolder> {

//List to store all items
List<ItemList> items;

//Constructor of this class
public Item_Card_Adapter(List<ItemList> items){
    super();
    //Getting all items
    this.items = items;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_layout,parent,false);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(Item_Card_Adapter.ViewHolder holder, int position) {
    holder.itemName.setText(items.get(position).getItemName());
    holder.itemDesc.setText(items.get(position).getItemDescription());
    holder.itemPrice.setText(items.get(position).getItemPrice());
}

@Override
public int getItemCount() {return items.size();}

class ViewHolder extends RecyclerView.ViewHolder {
    @Bind(R.id.ItemName) TextView itemName;
    @Bind(R.id.ItemDesc) TextView itemDesc;
    @Bind(R.id.ItemPrice) TextView itemPrice;
    @Bind(R.id.cardView) CardView cardView;

    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }
  }
}

Item_Get_Activity活动类

 public class Item_Get_Activity extends AppCompatActivity {
@Bind(R.id.recyclerrView) RecyclerView recyclerView;
@Bind(R.id.progressBar) ProgressBar progressBar;
private List<ItemList> data;
private Item_Card_Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.item_get_activity);
    ButterKnife.bind(this);
    initViews();
}

private void initViews() {
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);
    getDataFromServer();
}

public void  getDataFromServer() {
    int i = 1;
    APIService service = ApiClient.getClient().create(APIService.class);

    Call<ItemArray> userCall = service.getItem(i);

    userCall.enqueue(new Callback<ItemArray>() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onResponse(Call<ItemArray> call, Response<ItemArray> response) {
            if(response.isSuccessful()){
                progressBar.setVisibility(View.GONE);
                data = response.body().getItem();
                adapter = new Item_Card_Adapter(data);
                recyclerView.setAdapter(adapter);
            }
        }

        @Override
        public void onFailure(Call<ItemArray> call, Throwable t) {
            Log.d("onFailure", t.toString());
        }
    });
   }
  }

1 个答案:

答案 0 :(得分:1)

您需要像这样更改ApiServices接口

Offset

然后在“活动”中更新调用方法

public interface APIService {
    @FormUrlEncoded
    @POST("GetItem.php")
    Call<ItemArray> getItem(@Field("Retailer_Id")int Retailer_Id);
}

由于您的api响应在Json对象内包含“列表”。您需要一个具有List变量的类。因此,改造将成功解析对public void getDataFromServer() { int i = 1; APIService service = ApiClient.getClient().create(APIService.class); Call<ItemArray> userCall = service.getItem(i); userCall.enqueue(new Callback<ItemArray>() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onResponse(Call<ItemArray> call, Response<ItemArray> response) { if(response.isSuccessful()){ progressBar.setVisibility(View.GONE); data = response.body().getItem(); adapter = new Item_Card_Adapter(data); recyclerView.setAdapter(adapter); } } @Override public void onFailure(Call<List<ItemList>> call, Throwable t) { Log.d("onFailure", t.toString()); } }); } 的响应

更新 演示代码链接https://github.com/Siddharth-Dev/RetrofitDemo
这也有您的代码和有效的API代码。