【问题标题】:How to show a list in Android by using retrofit library?如何使用改造库在 Android 中显示列表?
【发布时间】:2019-04-25 18:33:20
【问题描述】:

我必须在 Activity 中显示一个列表

我的 API 密钥是:

http://api.cuidadotechnologies.com/NSSPL/leave_dtls.php

使用 GSON 转换器和改造库。 这个 API 会像这样以 JSON 格式抛出响应

{
  "status": 0,
  "response_data": [
    {
      "id": "12",
      "uid": "USER00000003",
      "reason": "Test",
      "type": "Plan Leave",
      "SataDate": "2018-09-18",
      "EndDate": "2018-09-25",
      "ApprovedBy": "USER00000002",
      "ApprovedDate": "2018-09-18",
      "Status": "REJECTED",
      "Remarks": "Test Reject"
    },
    {
      "id": "13",
      "uid": "USER00000003",
      "reason": "Wedding",
      "type": "Plan Leave",
      "SataDate": "2018-01-28",
      "EndDate": "2018-02-05",
      "ApprovedBy": "USER00000002",
      "ApprovedDate": "2018-09-18",
      "Status": "APPROVED",
      "Remarks": "Ok"
    }
  ]
}

我是这种方法的新手,请帮助我一步一步地做到这一点。

【问题讨论】:

  • 您需要根据响应创建模型类。并在 retorfit 的回调中接收响应。
  • 嗨。欢迎来到堆栈溢出!要求您在发布问题之前使用 Google。在这里进行简单的搜索:stackoverflow.com/questions/26500036/using-retrofit-in-android
  • GSON 和 Retrofit 都与展示任何内容无关。改造是为了执行网络请求,GSON - 转换 JSON 模型。你到底有什么问题?不要指望我们只做你的工作而不是你。
  • 展示一些技能@MonodipRoyChowdhury
  • 如果您是新手,请使用 youtube。您可以找到许多逐步完成的视频。

标签: java android json gson retrofit


【解决方案1】:

试试这个方法。。 制作改造对象..

public class ApiClient {
private final static String BASE_URL = "http://api.cuidadotechnologies.com/NSSPL/";
public static ApiClient apiClient;
private Retrofit retrofit = null;

public static ApiClient getInstance() {
    if (apiClient == null) {
        apiClient = new ApiClient();
    }
    return apiClient;
}

//private static Retrofit storeRetrofit = null;

public Retrofit getClient() {
    return getClient(null);
}



private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}

}

为api调用制作接口。

public interface ApiInterface {
@GET("leave_dtls.php")
Call<ResponseData> getData();
}

为响应创建 pojo 类。

public class ResponseDataItem{

@SerializedName("Status")
private String status;

@SerializedName("uid")
private String uid;

@SerializedName("reason")
private String reason;

@SerializedName("ApprovedDate")
private String approvedDate;

@SerializedName("Remarks")
private String remarks;

@SerializedName("ApprovedBy")
private String approvedBy;

@SerializedName("id")
private String id;

@SerializedName("type")
private String type;

@SerializedName("EndDate")
private String endDate;

@SerializedName("SataDate")
private String sataDate;

public void setStatus(String status){
    this.status = status;
}

public String getStatus(){
    return status;
}

public void setUid(String uid){
    this.uid = uid;
}

public String getUid(){
    return uid;
}

public void setReason(String reason){
    this.reason = reason;
}

public String getReason(){
    return reason;
}

public void setApprovedDate(String approvedDate){
    this.approvedDate = approvedDate;
}

public String getApprovedDate(){
    return approvedDate;
}

public void setRemarks(String remarks){
    this.remarks = remarks;
}

public String getRemarks(){
    return remarks;
}

public void setApprovedBy(String approvedBy){
    this.approvedBy = approvedBy;
}

public String getApprovedBy(){
    return approvedBy;
}

public void setId(String id){
    this.id = id;
}

public String getId(){
    return id;
}

public void setType(String type){
    this.type = type;
}

public String getType(){
    return type;
}

public void setEndDate(String endDate){
    this.endDate = endDate;
}

public String getEndDate(){
    return endDate;
}

public void setSataDate(String sataDate){
    this.sataDate = sataDate;
}

public String getSataDate(){
    return sataDate;
}

}

最后的回应..

public class ResponseData {

@SerializedName("response_data")
private List<ResponseDataItem> responseData;

@SerializedName("status")
private int status;

public void setResponseData(List<ResponseDataItem> responseData){
    this.responseData = responseData;
}

public List<ResponseDataItem> getResponseData(){
    return responseData;
}

public void setStatus(int status){
    this.status = status;
}

public int getStatus(){
    return status;
}

}

以这种方式将 api 调用到片段或活动中..

 ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
    Call<ResponseData> responseDataCall=apiInterface.getData();
    responseDataCall.enqueue(new Callback<ResponseData>() {
        @Override
        public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
            if (response.isSuccessful() && response.body()!=null && response!=null){
                List<ResponseDataItem> data=response.body().getResponseData();
            }
        }

        @Override
        public void onFailure(Call<ResponseData> call, Throwable t) {
                t.printStackTrace();
        }
    });

【讨论】:

    【解决方案2】:

    您可以使用 POJO 类将 JSON 转换为类。使用以下网站将 JSON 转换为 POJO。

    http://www.jsonschema2pojo.org

    之后,您可以使用 Retrofit 调用 API 并获得响应。从本站获取参考:https://square.github.io/retrofit/

    转换成类后就可以使用Gson方法进行转换了。

    SomeModelClass responseModel = new Gson().fromJson(response, SomeModelClass.class);
    

    如果您不想手动操作,可以使用此addConverterFactory(GsonConverterFactory.create()) 改造方法将响应直接转换为类模型。

    最后,您可以使用ViewHolder Pattern 创建适配器并将该适配器与RecyclerView 一起使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      相关资源
      最近更新 更多