Retrofit不会调用onReponse和onFailure

时间:2018-02-20 19:04:37

标签: java android retrofit retrofit2

在我的情况下,我使用改装与rest api联系。不幸的是,当我开始时,它永远不会达到响应和onFailure状态。我检查了一行一行的调试行,看起来他继续行:call.enqueue(new Callback<Api>() {然后它返回到开始循环,再次继续到同一行并跳过两个语句,最后完成整个方法。当然问题是为什么?

public void ApiHit(String[] tags) {

    //retrofit
    TagApi tagApi = NetworkService.retrofit.create(TagApi.class);

    //recieve words from searchview, divide and put into string array
    for (int i=0; i < tags.length; i++){

        Call<Api> call = tagApi.getTasks(tags[i]);
        call.enqueue(new Callback<Api>() {

            @Override
            public void onResponse(Call<Api> call, Response<Api> response) {


                //recieve possible tags for one word and put it into list
                for (int i = 0; i < response.body().getResults().size(); i++) {
                    listTags.add(new RowModel(response.body().getResults().get(i).getTag(), response.body().getResults().get(i).getAbsRelevance()));

                }

                //sort whole list
                Collections.sort(listTags);

                //add first tags to list
                for (int y = 0; y < 3; y++) {
                    listTagsFinal.add(new RowModel(listTags.get(y).getName(), listTags.get(y).getPosition()));
                }

                if (!isTagognizerTag) {
                    listTagsFinal.add(new RowModel("tagognizer", 23477853));
                    isTagognizerTag = true;
                }

                //add rest tags to list
                for (int y = 3; y < listTags.size(); y++) {
                    listTagsRest.add(new RowModel(listTags.get(y).getName(), listTags.get(y).getPosition()));
                }

            }

            @Override
            public void onFailure(Call<Api> call, Throwable t) {
            }

        });

    }
    //final sort
    Collections.sort(listTagsFinal);
    Collections.sort(listTagsRest);

    for (int y = 0; listTagsFinal.size() < 30; y++) {
        listTagsFinal.add(new RowModel(listTagsRest.get(y).getName(), listTagsRest.get(y).getPosition()));
    }

} 

我在onCreate中的同一个类(mainactivity)中调用它 - 当用户接受输入的文本到searchView中时:

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


        ButterKnife.bind(this);
        listTags = new ArrayList<>();
        listTagsFinal = new ArrayList<>();
        listTagsRest = new ArrayList<>();

        //set Proxima Bold font on top textview
        Typeface typeface = Typeface.createFromAsset(getAssets(), "font/proximabold.ttf");
        tvTop.setTypeface(typeface);


        //search text handler
        svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                result = query.split(",?\\ ");
                for (int x = 0; x < result.length; x++) {
                    //  Log.d("ciacho", result[x] + "\n");

                }
                ApiHit(result);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //This is your adapter that will be filtered
                return false;
            }
        });


    }

那就是我的简单模型类:

public class RowModel implements Comparable<RowModel>{

    private String name;
    private float position;

    public float getPosition() {
        return position;
    }

    public void setPosition(float position) {
        this.position = position;
    }

    public String getName() {
        return name;
    }

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


    public RowModel(String name, float position) {
        this.name = name;
        this.position = position;
    }

    @Override
    public int compareTo(RowModel rowModel) {
        float comparePosition = ((RowModel) rowModel).getPosition();


        return (int) (this.position- comparePosition);
    }

和与rest通信的默认类:

public class Api {

    @SerializedName("geo")
    @Expose
    private List<Float> geo = null;
    @SerializedName("rank")
    @Expose
    private int rank;
    @SerializedName("results")
    @Expose
    private List<Result> results = null;
    @SerializedName("tag")
    @Expose
    private String tag;
    @SerializedName("tagExists")
    @Expose
    private boolean tagExists;

    public List<Float> getGeo() {
        return geo;
    }

    public void setGeo(List<Float> geo) {
        this.geo = geo;
    }

    public int getRank() {
        return rank;
    }

    public void setRank(int rank) {
        this.rank = rank;
    }

    public List<Result> getResults() {
        return results;
    }

    public void setResults(List<Result> results) {
        this.results = results;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public boolean isTagExists() {
        return tagExists;
    }

    public void setTagExists(boolean tagExists) {
        this.tagExists = tagExists;
    }

}

并实施我的改造课程:

public class NetworkService {

    public static final Interceptor loggingInterceptor = new HttpLoggingInterceptor()
            .setLevel(HttpLoggingInterceptor.Level.BODY);

    public static final OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .build();

    public static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://api.xxx.com")
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient)
            .build();

和最后一堂课:

public interface TagApi {


    @GET("/tag/{tagId}")
    Call<Api> getTasks(
            @Path("tagId") String tagId);


}

2 个答案:

答案 0 :(得分:0)

在Retrofit 2中,您应该在baseUrl的末尾添加/

public static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://api.xxx.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient)
            .build();

并且您不应该在端点路径前放置/

public interface TagApi {
    @GET("tag/{tagId}")
    Call<Api> getTasks(
            @Path("tagId") String tagId);

}

查看示例here

答案 1 :(得分:0)

call.enqueue是一个异步操作,第一个FOR循环将在call.enqueue之后继续运行。如果要阻止直到收到响应,则需要使用同步call.execute

如果你在FOR循环下面发表评论并在onResponse()中加入一个断点,我认为你应该看到断点被击中。

for (int y = 0; listTagsFinal.size() < 30; y++) {
    listTagsFinal.add(new RowModel(listTagsRest.get(y).getName(), listTagsRest.get(y).getPosition()));
}