【发布时间】: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