简体   繁体   English

Android无法对服务器进行GET改装API调用

[英]Android failed GET retrofit API call to server

I am working on a Android project. 我正在开发一个Android项目。 I am using retrofit to call API's. 我正在使用改型来调用API。 So I am doing an API call to get the list of courses associated with certificate. 因此,我正在进行API调用以获取与证书相关的课程列表。

Response from the server get (BASE_URL/certificates/1) is: 来自服务器get(BASE_URL / certificates / 1)的响应是:

{
  "id": 1,
  "name": "Arts-certificate",
  "authorized_by": "priya",
  "created_by": "self",
  "created_by_id": "1",
  "description": "awarded to the best",
  "doc_url": "http://f8rentals.com/wp-content/uploads/2015/03/IMG_0067ft.jpg?189db0",
  "category_id": "2",
  "cateogory": "Arts",
  "courses": [
    {
      "id": 1,
      "course_id": "CRSXQHGZ0SCTLhklhk6JL",
      "number_of_sessions": 1,
      "created_at": "2015-12-16T07:10:37.000+00:00",
      "updated_at": "2015-12-16T07:10:37.000+00:00",
      "tags": null
    },
    {
      "id": 1,
      "course_id": "CRSXQHGZ0SCTLhklhk6JL",
      "number_of_sessions": 1,
      "created_at": "2015-12-16T07:10:37.000+00:00",
      "updated_at": "2015-12-16T07:10:37.000+00:00",
      "tags": null
    }
    .
    .
    .
    .
  ]
}

I have lists of certificates and required action is, upon clicking the certificate, it should take to new fragment which have all the courses associated with this certificate (on which click is made). 我有证书列表,并且需要采取的措施是,在单击证书后,它应该转到具有与该证书相关联的所有课程的新片段(在其中单击)。 For this I make the above API call. 为此,我进行了上述API调用。

Problem is when I click the first certificate in the list it goes to next fragment and list all the courses. 问题是,当我单击列表中的第一个证书时,它将转到下一个片段并列出所有课程。 But when I click any other certificate, it shows the blank fragment. 但是,当我单击任何其他证书时,它将显示空白片段。 When I Debug the code, in the fetchCourses() CoursesListOfCertificatesFragment.java , the onFailure() function is called. 当我调试代码时,在fetchCourses() CoursesListOfCertificatesFragment.java中 ,将调用onFailure()函数。

Workflow is CertificateFragment is the class which lists all the certificates. 工作流程为CertificateFragment是列出所有证书的类。 And on click, CertificateClickListner() in CertificateFragment, is triggered and in turn launches CoursesListOfCertificatesFragment with certificate object passed in constructor of this fragment. 单击后,会触发CertificateFragment中的CertificateClickListner()并依次启动CoursesListOfCertificatesFragment,并在此片段的构造函数中传递证书对象。 Here I make the API call GET (BASE_URL/certificates/1). 在这里,我将API调用为GET(BASE_URL / certificates / 1)。

This is in fetchCourses() in CoursesListOfCertificatesFragment. 这在CoursesListOfCertificatesFragment中的fetchCourses()中。 But except for 1st certificate, onFailure() method is called. 但是,除了第一个证书之外,还会调用onFailure()方法。

Any help is appreciated..... If any other information is required please ask. 感谢您的帮助。....如果需要其他信息,请询问。

Thanks. 谢谢。

Below are the relevant classes listed: 以下是列出的相关类别:

CoursesListOfCertificatesFragment.java CoursesListOfCertificatesFragment.java

package com.localjini.learner.fragments;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.localjini.learner.R;
import com.localjini.learner.adapters.CourseListingRVAdapter;
import com.localjini.learner.api.RestClient;
import com.localjini.learner.main.HomeActivity;
import com.localjini.learner.models.Certificates;
import com.localjini.learner.models.Course;
import com.localjini.learner.models.CoursesResponse;
import com.localjini.learner.models.GetCertificateResponse;
import com.localjini.learner.utils.LogUtils;
import com.localjini.learner.utils.UIHelper;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;


public class CoursesListOfCertificatesFragment extends BaseFragment {

    @Bind(R.id.tv_category)
    TextView tvCategory;
    @Bind(R.id.tv_sort_filter)
    TextView tvSortFilter;
    @Bind(R.id.pb_course_listing)
    ProgressBar pbCourseListing;
    @Bind(R.id.rv_course_listing)
    RecyclerView rvCourseListing;

    public UIHelper uiHelper;
    List<Course> courses;

    private Certificates certificate;
    private int certificate_id;

    public CoursesListOfCertificatesFragment(){

    }

    private CourseListingRVAdapter.CourseClickListener listener = new CourseListingRVAdapter.CourseClickListener() {

        @Override
        public void onCourseClicked(Course course) {
            interactionListener.launchCourseDetailFragment();
        }
    };

    public CoursesListOfCertificatesFragment(Certificates certificate){
        this.certificate = certificate;
        this.certificate_id = certificate.getId();
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (root == null) {
            root = (ViewGroup) inflater.inflate(R.layout.fragment_course_listing, container, false);

            ButterKnife.bind(this, root);

            initInstances();

            fetchCourses();
        }


        return root;
    }

    private void initInstances() {
        uiHelper = new UIHelper(getActivity());

        ((HomeActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
        ((HomeActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ((HomeActivity) getActivity()).getSupportActionBar().setTitle("");

        rvCourseListing.setItemAnimator(new DefaultItemAnimator());
        rvCourseListing.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvCourseListing.setHasFixedSize(true);
    }

    private void fetchCourses() {
        Call<GetCertificateResponse> call = RestClient.getCMSServiceInstance().getCertificateById(certificate_id);
        call.enqueue(new Callback<GetCertificateResponse>() {
            @Override
            public void onResponse(Response<GetCertificateResponse> response, Retrofit retrofit) {

                if (response != null) {
                    GetCertificateResponse resp = response.body();

                    if (resp != null) {
                        showCourses(resp.getCourses());
                    } else {
                        uiHelper.showToast("response contain null data");
                    }
                }
            }

            @Override
            public void onFailure(Throwable t) {
                LogUtils.d("coursesFailed", t.getMessage());
            }
        });

    }

    private void showCourses(List<Course> courses) {
        if(courses != null) {
            CourseListingRVAdapter courseListingRVAdapter = new CourseListingRVAdapter(getActivity(), courses);
            courseListingRVAdapter.setCourseClickListener(listener);
            rvCourseListing.setAdapter(courseListingRVAdapter);
        }
    }

    public FragmentId getFragmentId() {
        return FragmentId.COURSE_LISTING_FRAGMENT;
    }

}

CertificateFragment.java CertificateFragment.java

public class CertificateFragment extends BaseFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    //protected ViewGroup root;
    protected Context context;
    @Bind(R.id.rv_Certificates) RecyclerView rvCertificates;

    private CertificateRVAdapter.CertificateClickListener listener = new CertificateRVAdapter.CertificateClickListener() {

        @Override
        public void onCertificateClicked(Certificates certificate) {
            Toast.makeText(getActivity(), certificate.getName() +" Clicked", Toast.LENGTH_SHORT).show();
            //interactionListener.launchCourseListingFragment();
            interactionListener.launchCoursesListOfCertificatesFragment(certificate);
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if(root==null) {

            root = (ViewGroup) inflater.inflate(R.layout.fragment_certificate, container, false);
            ButterKnife.bind(this, root);

            initInstances();
            getCertificates();
        }
        return root;
    }
//    rvCourseListing.setItemAnimator(new DefaultItemAnimator());
//    rvCourseListing.setLayoutManager(new LinearLayoutManager(getActivity()));
//    rvCourseListing.setHasFixedSize(true);
//

    private void initInstances() {
        //uiHelper = new UIHelper(getActivity());

        ((HomeActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
        ((HomeActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ((HomeActivity) getActivity()).getSupportActionBar().setTitle("");

        rvCertificates.setItemAnimator(new DefaultItemAnimator());
        rvCertificates.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvCertificates.setHasFixedSize(true);
    }

    private void getCertificates() {

        Call<AllCertificateResponse> call = RestClient.getCMSServiceInstance().getCertificates();

        call.enqueue(new Callback<AllCertificateResponse>() {
            @Override
            public void onResponse(Response<AllCertificateResponse> response, Retrofit retrofit) {
                if (response.isSuccess()) {
                    //com.squareup.okhttp.Response raw = response.body().raw();

                    List<Certificates> certificates = response.body().getCertificates();
                    if (certificates != null)
                        showCertificates(certificates);

                    Toast.makeText(getActivity(), "Success in getting certificates", Toast.LENGTH_SHORT).show();
                } else {
                    Log.d("CERT", "response is failure");
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Toast.makeText(getActivity(), "Failure", Toast.LENGTH_SHORT).show();
            }

        });
    }

    public void showCertificates(List<Certificates> certificates){

        CertificateRVAdapter adapter = new CertificateRVAdapter(getActivity(), certificates);
        adapter.setCertificateClickListener(listener);
        rvCertificates.setAdapter(adapter);
    }

    public FragmentId getFragmentId() {
        return FragmentId.COURSE_LISTING_FRAGMENT;
    }

}

I fixed the problem. 我解决了这个问题。 Turns out server was giving the wrong response( it is still in testing phase). 事实证明服务器给出了错误的响应(它仍处于测试阶段)。 I was expecting array of strings. 我期待的是字符串数组。 While for 1st certificate, all courses had array of strings, but for 2nd onward, all had string values instead of arrays. 对于第一个证书,所有课程都具有字符串数组,但是对于第二个以后,所有课程都具有字符串值而不是数组。

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

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