Android Retrofit库始终返回null

时间:2017-09-18 18:19:45

标签: java android null retrofit

我正在尝试使用Retrofit与服务器通信,但我总是得到null引用。

API:http://gaborbencebekesi.hu/vote/api/get/questions

在应用程序中,我有一个模型类:

公共课问题{

public String question;
public String uploader;
public boolean password;
public String url;

public Question(String question, String uploader, boolean password, String url) {
    this.question = question;
    this.uploader = uploader;
    this.password = password;
    this.url = url;
}

}

和网络课程。

公共类网络{

private final String API_URL = "http://gaborbencebekesi.hu/vote/";

private Retrofit retrofit;

private interface Questions {
    @GET("api/get/questions/")
    Call<List<Question>> get();
}

public Network() {
    retrofit = new Retrofit.Builder()
            .baseUrl(API_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

public List<Question> GetQuestions() throws IOException {

    // Create an instance of our GitHub API interface.
    Questions questions = retrofit.create(Questions.class);

    // Create a call instance for looking up Retrofit contributors.
    Call<List<Question>> call = questions.get();

    // Fetch and print a list of the contributors to the library.
    List<Question> q = call.execute().body();
    if(q == null) System.err.println("list is null");
    return q;

}

}

最后一个函数总是返回null。

有人知道如何解决它吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

你可能会得到这个,因为你正在主线程上进行此调用。做这样的事情:

public void GetQuestions() throws IOException {

    // Create an instance of our GitHub API interface.
    Questions questions = retrofit.create(Questions.class);

    // Create a call instance for looking up Retrofit contributors.
    Call<List<Question>> call = questions.get();

    // Fetch and print a list of the contributors to the library.
    call.enqueue(this);
}

您应该实现回调并在回调中处理响应。

答案 1 :(得分:0)

请使用异步调用,而不是使用同步调用,所以请更改您的代码

Call<List<Question>> call = questions.get();
        call.enqueue(new Callback<List<Question>>() {
            @Override
            public void onResponse(Call<List<Question>> call, retrofit2.Response<List<Question>> response) {
                if (response.body != null) {
                    for (int i = 0; i < response.body.size(); i++)
                        log.e("response", response.body.get(i));
                }
            }

            @Override
            public void onFailure(Call<List<Question>> call, Throwable t) {
                  //handle fail
            }
        });