Retrofit Get Data Object

Tags: ,



I have a data like this, and i want get report and criteria data.

{
    "response_code": 200,
    "message": "Your report data has been loaded.",
    "data": {
        "report": [
            {
                "id_report": 1,
                "report_name": "report name A"
            },
            {
                "id_report": 2,
                "report_name": "report name B"
            }
        ],
        "criteria": [
            {
                "id_criteria": 1,
                "criteria_name": "criteria name A"
            },
            {
                "id_criteria": 2,
                "criteria_name": "criteria name B"
            }
        ]
    }
}

And i get data in java using retrofit. And this is my java class.

GetReport.java

    @SerializedName("response_code")
    private int response_code;
    @SerializedName("status")
    private boolean status;
    @SerializedName("message")
    private String message;
    @SerializedName("data")
    Call<Data> listData;

Data.java

    @SerializedName("report")
    private List<Report> reportList;
    @SerializedName("criteria")
    private List<Criteria> criteriaList;

And this how i call the data.

public void populateData() {
        Call<GetReport> getReportCall = apiInterface.getReportCall();
        getReportCall.enqueue(new Callback<GetReport>() {
            @Override
            public void onResponse(Call<GetReport> call, Response<GetReport> response) {
                response.body().getListData().enqueue(new Callback<Data>() {
                    @Override
                    public void onResponse(Call<Data> call, Response<Data> response) {
                        List<Report> reportList = response.body().getReportList();

                        Log.d("TAGGGGGGGGGG", String.valueOf(reportList.size()));
                    }

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

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

When I run the program, my activity closes immediately. When I look at logcat, there is too much running log data so I can’t see where the error is.

Answer

I have managed to attempt and solve your problem with the following code. I copied and pasted the JSON you provided above at JSONbin.io so that I can be able to call it using an API call. I did not modify the structure of the JSON at all.

App build.gradle

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

GetReport.java

package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class GetReport {

@SerializedName("response_code")
int response_code;

@SerializedName("message")
String message;

@SerializedName("data")
Data data;

public int getResponse_code() {
    return response_code;
}

public void setResponse_code(int response_code) {
    this.response_code = response_code;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public Data getData() {
    return data;
}

public void setData(Data data) {
    this.data = data;
}}

Data.java

package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
import java.util.List;

public class Data {

@SerializedName("report")
List<Report> reportList;

@SerializedName("criteria")
List<Criteria> criteriaList;

public List<Report> getReportList() {
    return reportList;
}

public void setReportList(List<Report> reportList) {
    this.reportList = reportList;
}

public List<Criteria> getCriteriaList() {
    return criteriaList;
}

public void setCriteriaList(List<Criteria> criteriaList) {
    this.criteriaList = criteriaList;
}}

Criteria.java

package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class Criteria {

@SerializedName("id_criteria")
int id_criteria;

@SerializedName("criteria_name")
String criteria_name;

public Criteria(int id_criteria, String criteria_name) {
    this.id_criteria = id_criteria;
    this.criteria_name = criteria_name;
}

public int getId_criteria() {
    return id_criteria;
}

public void setId_criteria(int id_criteria) {
    this.id_criteria = id_criteria;
}

public String getCriteria_name() {
    return criteria_name;
}

public void setCriteria_name(String criteria_name) {
    this.criteria_name = criteria_name;
}}

Report.java

package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class Report {

@SerializedName("id_report")
int id_report;

@SerializedName("report_name")
String report_name;

public Report(int id_report, String report_name) {
    this.id_report = id_report;
    this.report_name = report_name;
}

public int getId_report() {
    return id_report;
}

public void setId_report(int id_report) {
    this.id_report = id_report;
}

public String getReport_name() {
    return report_name;
}

public void setReport_name(String report_name) {
    this.report_name = report_name;
}}

RetrofitClient.java

package com.example.retrofitapp.api;
import com.google.gson.*;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
public static Retrofit retrofit;

public static Retrofit getRetrofitClient(String baseUrl){
    if(retrofit==null){
        Gson gson = new GsonBuilder().setLenient().create();
        retrofit = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create(gson)).build();
    }
    return retrofit;
}}

Constants.java

package com.example.retrofitapp;

public class Constants {
   public static String base_url = "https://api.jsonbin.io/";
}

Api.java

package com.example.retrofitapp.api;
import com.example.retrofitapp.GetReport;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;

public interface Api {

@Headers("Secret-key:$2a$10$WxkkTylkdR7NwGSoPwrfy.Odxtj7MR2vDtYZBp9cOd0SaYGVRmhOm")
@GET("/b/5ff8172e63e86571a2e35639")
Call<GetReport> getReport();

}

MainActivity.java

package com.example.retrofitapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.retrofitapp.api.Api;
import com.example.retrofitapp.api.RetrofitClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      //call method here
      populateData();
    }

   private void populateData() {
      Retrofit retrofit = RetrofitClient.getRetrofitClient(Constants.base_url);
      Api api = retrofit.create(Api.class);
      Call<GetReport> getReportCall = api.getReport();

      //make asynchronous request
      getReportCall.enqueue(new Callback<GetReport>() {
          @Override
          public void onResponse(Call<GetReport> call, Response<GetReport> response) { 
            if(response.code()  == 200){
                GetReport getReport = (GetReport) response.body();
                
                  //get response code
                int responseCode = getReport.getResponse_code();
                
                //get message 
                String message = getReport.getMessage();
                
                //get data
                Data data = getReport.getData();
                
                //get reports(loop)
                for(Report report : data.getReportList()){
                    //your report here
                }

                //get criteria(loop)
                for(Criteria criteria : data.getCriteriaList()){
                    //your criteria here
                }
              }
           }
          @Override
          public void onFailure(Call<GetReport> call, Throwable t) {
            //do something if the request failed
          }
      });

  }}

That is how I solved it.



Source: stackoverflow