如何通过Retrofit2使用API​​调用?

时间:2019-02-11 13:31:02

标签: java android rest retrofit2

API文件

方法:获取

OUTPUT:
{
    "status": true,
    "message": "Subjects found.",
    "data": {
        "subjects": [
            {
                "subj_id": "2",
                "name": "Maths",
                "img": "Math.jpg"
            },
            {
                "subj_id": "1",
                "name": "Physics",
                "img": "physics.png"
            }
        ],
        "total": 2
    }
}

模型类

public class SubjectTopics
{

@SerializedName("status")
@Expose
private Boolean status;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private Data data;

public Boolean getStatus() {
    return status;
}

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

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;
}
}

public class Data {


@SerializedName("subjects")
@Expose
private List<Subjects> subjects = null;
@SerializedName("total")
@Expose
private Integer total;

public List<Subjects> getSubjects() {
    return subjects;
}

public void setSubjects(List<Subjects> subjects) {
    this.subjects = subjects;
}

public Integer getTotal() {
    return total;
}

public void setTotal(Integer total) {
    this.total = total;
}

}

public class Subjects {


@SerializedName("subj_id")
@Expose
private String subjId;
@SerializedName("name")
@Expose
private String name;
@SerializedName("img")
@Expose
private String img;


public String getSubjId() {
    return subjId;
}

public void setSubjId(String subjId) {
    this.subjId = subjId;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getImg() {
    return img;
}

public void setImg(String img) {
    this.img = img;
}

}

我的适配器

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> {

        private List<Subjects> movies;
        private int rowLayout;
        private Context context;


        public static class MovieViewHolder extends RecyclerView.ViewHolder {
            private TextView subjectName;
            private TextView ID;
            private ImageView ImageV;
            private RelativeLayout relativeClick;


            public MovieViewHolder(View v) {
                super(v);

                subjectName = (TextView) itemView.findViewById(R.id.textView);
                relativeClick = (RelativeLayout) itemView.findViewById(R.id.relative_click);
                ImageV = (ImageView) itemView.findViewById(R.id.imageView);

            }

        }



        public MoviesAdapter(List<Subjects> movies, int rowLayout, Context context) {

            this.movies = movies;
            this.rowLayout = rowLayout;
            this.context = context;
        }



        @Override
        public MoviesAdapter.MovieViewHolder onCreateViewHolder(ViewGroup parent,
                                                                int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
            return new MoviesAdapter.MovieViewHolder(view);

        }




    @Override
        public void onBindViewHolder(MoviesAdapter.MovieViewHolder holder, final int position) {

            holder.subjectName.setText(movies.get(position).getName());



            holder.relativeClick.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


                    Intent intent = new Intent(context, SubjectTopicList.class);

                    intent.putExtra("subject_id", movies.get(position).getSubjId());

                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    context.startActivity(intent);


                }

            });


            Picasso.with(context)
                    .load(movies.get(position).getImg())
                    .placeholder(R.drawable.load)
                    .into(holder.ImageV);


        }


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


    }

活动

private void getSubjects() {

        progressBar.setVisibility(View.VISIBLE);

        Call<SubjectTopics> getProductsModelClassCall = webService.getSubjects();

        getProductsModelClassCall.enqueue(new Callback<SubjectTopics>() {
            @Override
            public void onResponse(Call<SubjectTopics> call, Response<SubjectTopics> response) {
                if (response.isSuccessful()) {

                    List<Subjects> movies = response.body().getData().getSubjects();

                    MoviesAdapter newAd=new MoviesAdapter(movies, R.layout.unit_test_row, getApplicationContext());

                    recyclerView.setAdapter(newAd);



                } else {
                    APIError apiError = ErrorUtils.parseError(response);

                    Toast.makeText(UnitTestSubjects.this, ""+apiError, Toast.LENGTH_SHORT).show();

                }

                if (progressBar.isEnabled())
                    progressBar.setVisibility(View.INVISIBLE);
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(Call<SubjectTopics> call, Throwable t) {
                Toast.makeText(UnitTestSubjects.this, "Please Try Again", Toast.LENGTH_SHORT).show();
                if (progressBar.isEnabled())
                    progressBar.setVisibility(View.INVISIBLE);
                progressBar.setVisibility(View.GONE);
            }
        });


    }

改装代码

public class ServiceGenerator {
    private final static String TAG = "ApiCall";


    public static Retrofit getRetrofit(){
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        // set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        // add your other interceptors …

        // add logging as last interceptor
        httpClient.addInterceptor(logging);  // <-- this is the important line!
        httpClient.connectTimeout(10, TimeUnit.SECONDS).readTimeout(14, TimeUnit.SECONDS).writeTimeout(16, TimeUnit.SECONDS);

        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .create();

        return new Retrofit.Builder()
                .baseUrl(WebServices.BASE_URL)
                .client(httpClient.build())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }


    public static Api getApi(){
        return  getRetrofit().create(Api.class);
    }
}

使用Retrofit 2.0调用API后,无法获得任何响应并得到此错误:

  

失败:   retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall@5321

每次回调后,它直接从方法

中出来

我已经尝试了所有可能的方法来解决,但是找不到任何解决方案。

我认为这是内部改造错误,或者是在pojo类中。请帮忙!

0 个答案:

没有答案