2017-06-22 28 views
0

在MainActivity.java //根URL我們的Web服務的 公共靜態最後絃樂ROOT_URL =「http://pratikbutani.x10.mx」; RestAdapter adapter = new RestAdapter.Builder() .setEndpoint(ROOT_URL) .build();成敗方法不調用使用改裝Android中

//Creating an object of our api interface 
    BooksAPI api = adapter.create(BooksAPI.class); 

    //Defining the method 
    api.getBooks(new Callback<List<Contact>>() { 
     @Override 
     public void success(List<Contact> list, Response response) { 
      //Dismissing the loading progressbar 

      //Storing the data in our list 
      books = list; 

      //Calling a method to show the list 
      showList(); 
     } 

     @Override 
     public void failure(RetrofitError error) { 
      //you can handle the errors here 
     } 
    }); 

公共接口BooksAPI {

/*Retrofit get annotation with our URL 
    And our method that will return us the list ob Book 
*/ 
@GET("/json_data.json") 
public void getBooks(Callback<List<Contact>> response); 

}

回答

0

//改型類

public class NetworkContext { 

private static final String BASE_URL = "https://xyz/"; 

private Map<String, Object> services; 

private Retrofit retrofit; 

private static final NetworkContext INSTANCE = new NetworkContext(); 

private NetworkContext() { 
    services = new HashMap<>(); 
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); 
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); 
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); 

    retrofit = new Retrofit.Builder() 
      .baseUrl(BASE_URL) 
      .addConverterFactory(GsonConverterFactory.create()) 
      .client(client) 
      .build(); 
} 

public static NetworkContext getInstance() { 
    return INSTANCE; 
} 

public synchronized <T> T getService(Class<T> clazz) { 
    String key = clazz.getName(); 
    if (services.containsKey(key)) { 
     return (T) services.get(key); 
    } else { 
     T newClass = retrofit.create(clazz); 
     services.put(key, newClass); 
     return newClass; 
    } 
}  
} 

// API接口

public interface APIInterface { 

@GET("will be attached with the base url") 
Call<Model> getData(); 
} 

//致電

Call call = apiInterface.getData(); 
    call.enqueue(new Callback() { 
     @Override 
     public void onResponse(Call call, Response response) { 
      Model model = (Model) response.body(); 
      // here you can retrieve data 
     } 

     @Override 
     public void onFailure(Call call, Throwable t) { 
      call.cancel(); 
     } 
    }); 
+0

我應該在哪裏放置代碼//調用代碼。 –

+0

在您的活動或片段中(或者如果您遵循MVP架構,則爲演示者) –

相關問題