2017-09-18 2 views
0

Retrofit을 사용하여 서버와 통신하려고하지만 항상 null 참조를받습니다.Android Retrofit 라이브러리는 항상 null을 반환합니다.

이 API :

공용 클래스 질문 {

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

}

및 네트워크 클래스 : 응용 프로그램에서 http://gaborbencebekesi.hu/vote/api/get/questions

나는 모델 클래스가 있습니다.

공용 클래스 네트워크 {

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 
      } 
     }); 
관련 문제