gpt4 book ai didi

java - 从 onSuccess 调用方法到另一个类

转载 作者:行者123 更新时间:2023-12-01 13:20:20 25 4
gpt4 key购买 nike

我是 java/android 开发新手,所以如果可以的话请提供帮助。

我想要一个从 Web 服务(异步)获取数据的方法,一旦完成(onSuccess 或 onFailure),它应该调用 Activity 类上的另一个方法。假设我有 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 中,我想调用 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
}

我怎样才能实现这样的目标?提前致谢

最佳答案

  1. 创建界面

    public interface ResponseListener {
    void onObject1DataDownload(JSONObject jsonObject);
    }
  2. 将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
    }
    });
    }
  3. 在您的 Activity 中实现界面

    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 方法注册回调。

关于java - 从 onSuccess 调用方法到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22075355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com