我以前在活动中有我的createBottomBar()。由于活动跨越了4-5行,所以我将它移到一个单独的类中,但现在我不知道如何访问我的updateMap()。
updateMap代码是:
private void updateMap(String path) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
MyService service = restAdapter.create(MyService.class);
service.points(path, context);
}其中接口是:
public interface MyService {
@GET("/{point}")
void points(@Path("point") String path, MainActivity cb);
}我应该在哪里/如何移动/更改更新的回调,这样我才能让它继续工作?
PS :我知道这更像是一个java问题,而不是一个android。
发布于 2015-05-10 07:11:40
用于回调的类必须实现Callback<T>接口。请参阅前面的更多信息,改装文档,这样回调不依赖于活动类,而是取决于回调接口的实现。因此,您可以将updateMap()方法放入您喜欢的任何类中,因为它不依赖于上下文。下面是一个简短的例子
所以您的界面可能如下所示
public interface MyService {
@GET("/{point}")
void points(@Path("point") String path, Callback<YourClassType>);
}并且可以在匿名类中内联地定义回调实现。
MyService service = restAdapter.create(MyService.class);
service.points(path, new Callback<YourClassType>)() {
@Override
public void success(YourClassType foo, Response response)
{
// success
}
@Override
public void failure(RetrofitError error) {
// something went wrong
}
}); 希望这能解决你的问题?
编辑:也请注意,每次你想要做一个请求时,你都不必重新创建Rest客户端。只做一次就够了。因此,也许可以为restclient定义一个类对象并重用它。
public class MyRestClientClass{
//class context
MyService mService;
//helper method for service instantiation. call this method once
void initializeRestClient()
{
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
mService = restAdapter.create(MyService.class);
}
//your service request method
void updateMap()
{
mService.points(....)
}
}例如,在下面的活动中使用这个类是一个简短的虚拟代码。
MyRestClientClass mRestClientClass = new MyRestClientClass();
//instantiate the rest client inside
mRestClientClass.initializeRestClient();
//to call your updateMap for example after a button click
yourButton.setOnClickListener(new OnClickListener() {
//note that this works the same way as the Retrofit callback
public void onClick(View v) {
//call your web service
mRestClientClass.updateMethod();
}
});https://stackoverflow.com/questions/30148489
复制相似问题