【问题标题】:Making http request using retrofit from non activity class使用非活动类的改造发出 http 请求
【发布时间】:2015-11-20 20:39:44
【问题描述】:

我们在开发时在我的应用中使用了 Activity-BL-DAO-DB(sqlite)。

由于需求变化,我们必须单独使用服务器的 REST 服务。我见过改造它。但我不确定如何在 DAO 类而不是 SQL 查询中使用它。

我们研究了需要更多返工的总线概念。我们希望对代码进行最小的更改以包含此更改。

如果还有什么需要,请告诉我。

例如: 以下是将在列表中显示技术列表的示例流程。

技术活动 OnCreate 方法:

    techList=new ArrayList<Technology>();
    techList=technologyBL.getAllTechnology(appId);
    adapterTech=new TechnologyAdapter(this,new ArrayList<Technology>  (techList));
    listView.setAdapter(adapterTech);

技术BL:

    public List<Technology> getAllTechnology(String appId) {
        techList=technologyDao.getAllTechnology(appId);
        // some logic 
        return techList;
    }

技术 DAO:

    public List<Technology> getAllTechnology(String appId) {
        //sql queries
        return techList;
    }

技术模型:

   class Technology{
        String id,techName,techDescription;
       //getters & setters
   }

我必须用改造请求替换 sql 查询。我创建了以下改造类和接口:

RestClient 接口:

    public interface IRestClient {

      @GET("/apps/{id}/technologies")
      void getTechnoloies(@Path("id") String id,Callback<List<Technology>> cb);

      //Remaining methods
    }

休息客户端:

    public class RestClient {

          private static IRestClient REST_CLIENT;
          public static final String BASE_URL = "http://16.180.48.236:22197/api";
          Context context;

          static {
             setupRestClient();
          }

          private RestClient() {}

          public static RestClient get() {
             return REST_CLIENT;
          }

          private static void setupRestClient() {
               RestAdapter restAdapter = new RestAdapter.Builder()
                  .setEndpoint(BASE_URL)
                  .setClient(getClient())
                  .setRequestInterceptor(new RequestInterceptor() {
                  //cache related things
               })
               .setLogLevel(RestAdapter.LogLevel.FULL)
               .build();

               REST_CLIENT = restAdapter.create(IAluWikiClient.class);
           }

           private static OkClient getClient(){
                 //cache related
           }
    }

我尝试在 DAO 中同时使用同步/异步方法进行调用。对于同步方法,它抛出了一些与主线程相关的错误。对于异步,它由于请求延迟完成而崩溃。

在 DAO 中同步调用:

    techList=RestClient.get().getTecchnologies(id);

DAO 中的异步调用:

    RestClient.get().getTechnolgies(id,new CallBack<List<Technolgy>(){
       @Override
       public void success(List<Technology> technologies, Response response)   {
            techList=technologies;
       }

       @Override
       public void failure(Retrofit error){}
   });

【问题讨论】:

  • 我对你的要求有点困惑。您想用 Retrofit 替换 SQL 查询吗?在 Activity 之外使用 RetrofitAdapter 应该很简单。发布一些现有代码并说明您尝试使用它更新的内容可能会很好。
  • 是的。我想用改造调用替换 sql 查询。我添加了代码流。希望能帮助到你。 :)

标签: java android rest http retrofit


【解决方案1】:

这里有两个选项。

首先是在Activity中创建Retrofit回调:

RestClient.get().getTechnolgies(id,new CallBack<List<Technolgy>(){
   @Override
   public void success(List<Technology> technologies, Response response) {
        ArrayList<Technology> techList = technologyBL.someLogic(technologies);
        adapterTech=new TechnologyAdapter(this,techList);
        listView.setAdapter(adapterTech);
   }

   @Override
   public void failure(Retrofit error){}
});

请注意,您必须将 //some logic 部分提取到单独的 BL 方法中。

第二个选项是让 Retrofit API 调用返回一个 RxJava Observable(集成到 Retrofit 中):

RestClient.get().getTechnolgies(id)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<List<Technology>>() {
         @Override
            public void call(List<Technology> technologies) {
                ArrayList<Technology> techList = technologyBL.someLogic(technologies);
                adapterTech=new TechnologyAdapter(this,techList);
                listView.setAdapter(adapterTech);
            }
     });

在这种情况下,您的 RestClient 接口是:

public interface IRestClient {

  @GET("/apps/{id}/technologies")
  Observable<List<Technology>> getTechnologies(@Path("id") String id);

  //Remaining methods
}

您可以在http://square.github.io/retrofit/ 的“SYNCHRONOUS VS. ASYNCHRONOUS VS. OBSERVABLE”部分了解更多信息。另外,请参阅 these two 博客文章,了解 RxJava 和 Observables:

【讨论】:

【解决方案2】:

根据我的经验,我发现创建一个Service 非常有用,它通过使用自定义AsyncTask 实现来执行对Retrofit API 的调用。这种范式将所有数据模型交互保存在一个位置(服务),并使所有 API 调用脱离主线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多