我是java / android开发的新手,所以请尽可能帮忙。
我想有一个从Web服务(异步)获取数据的方法,一旦完成(onSuccess或onFailure),它应该在活动类上调用另一个方法。 让我说我有WebManager类,这不是真正的方法,我将添加更多仍然加上try / catch等等:
public class WebManager {
public MyObject1 getObject1() {
AsyncHttpClient client = new AsyncHttpClient();
client.get(QUERY_URL,
new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject jsonObject) {
//Call method on my Activity and pass jsonObject (in the other method I want to pass my custom object instead of json)
}
@Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
//Call method on my Activity and pass statusCode, throwable and error
}
});
}
public MyObject2 getObject2() {
AsyncHttpClient client = new AsyncHttpClient();
// The same as above
}
}
现在在我的MainActivity中我想调用let说的getObject1(),当数据下载时我想调用方法:
WebManager wm = new WebManager();
//...
protected void onObject1DataDownload(JSONObject jsonObject) {
//Do something with the data
}
protected void onObject2DataDownload(CUSTOMOBJECT obj) {
//Do something with the data
}
我怎样才能实现这样的目标? 提前致谢
答案 0 :(得分:1)
创建界面
public interface ResponseListener {
void onObject1DataDownload(JSONObject jsonObject);
}
将WebManager中的getObject1()方法更改为参数化方法,并调用回调方法。
public class WebManager {
public MyObject1 getObject1(ResponseListener listener) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(QUERY_URL,
new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject jsonObject) {
//here's the change
listener.onObject1DataDownload(jsonObject);
}
@Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
//Call method on my Activity and pass statusCode, throwable and error
}
});
}
在您的活动中实施界面
public class MainActivity implements ResponseListener{
public void someMethod() {
WebManager wm = new WebManager();
//pass the activity as the listener
wm.getObject1(this);
}
protected void onObject1DataDownload(JSONObject jsonObject) {
//this method will be called }
protected void onObject2DataDownload(CUSTOMOBJECT obj) { //Do something with the data }
}
同样,您可以为onFailure方法注册回调。
答案 1 :(得分:0)
更好的方法可能是使用处理程序和消息。
http://developer.android.com/reference/android/os/Handler.html
或者至少不要忘记通过以下方式在UI线程中运行UI相关代码:
runOnUiThread(new Runnable() {
@Override
public void run() {
// code
}
});