2017-09-18 108 views
0

我想用Retrofit與服務器通信,但我始終得到空引用。Android 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。

有沒有人有一個想法如何解決它?

謝謝!

+0

什麼是你的Questions.java文件? (不是Question.java) – ninjayoto

回答

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

您應該實現回調並處理回調中的響應。

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