2017-09-18 4 views
0

J'essaie de communiquer avec le serveur avec Retrofit, mais j'ai toujours une référence nulle.La bibliothèque Android Retrofit renvoie toujours une valeur nulle

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

Dans l'application, j'ai une classe de modèle:

Question public class {

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

}

et une classe de réseau.

réseau public class {

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; 

} 

}

dernière fonction retourne toujours null.

Est-ce que quelqu'un a une idée pour le résoudre?

Merci!

+0

Qu'est-ce que dans votre fichier Questions.java? (pas Question.java) – ninjayoto

Répondre

0

Vous obtenez probablement ceci parce que vous faites cet appel sur le fil principal. Faites quelque chose comme ceci:

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

Vous devez implémenter les rappels et gérer la réponse dans les rappels.

0

Au lieu d'utiliser l'appel synchrone, s'il vous plaît utiliser appel asynchrone, s'il vous plaît changer votre code

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