【问题标题】:Android loopj asynchttpclient return responseAndroid loopj asynchttpclient 返回响应
【发布时间】:2013-07-25 05:42:50
【问题描述】:

在我的一个项目中,我使用loopj asynchttpclient 与我的网站进行通信。 沟通部分运作良好并得到回应

我的活动看起来像

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        WebRequest test=new WebRequest();
        test.callService();
}

WebRequest 类为

public class WebRequest extends Activity {


    public void callService(){


        AsyncHttpClient client = new AsyncHttpClient();
        client.post("http://domain.com/dp/index.php", new AsyncHttpResponseHandler() {


            @Override
            public void onSuccess(String response) {
                Log.v("P",response);
            }

            @Override
            public void onFailure(Throwable e, String response) {
                 Log.v("PS",e.toString());
            }

    });
    }




}

我很困惑如何将响应返回给主要活动,以便我可以从该响应创建列表视图。

我是新手 请帮我 提前致谢

【问题讨论】:

    标签: android web-services android-layout android-asynctask loopj


    【解决方案1】:

    在您的 WebRequest 类中:

    • 我认为您不希望此类扩展Activity。只有在创建要在应用程序中显示的页面时,才应该扩展 Activity。您只是想执行一些代码,因此不需要扩展 Activity
    • 将您的呼叫服务方法更改为静态并将AsyncHttpClient 作为参数。

    您的 WebRequest 类现在应该如下所示:

    final class WebRequest {
        private AsyncHttpClient mClient = new AsyncHttpClient();
        public static void callService(AsyncHttpResponseHandler handler) {
            mClient.post("http://domain.com/dp/index.php", handler);
        }
    }
    

    在您的主要活动中:

    现在您在主要活动中所要做的就是像这样调用静态方法:

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);
            WebRequest.callService(new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    // Initiated the request
                }
    
                @Override
                public void onSuccess(String response) {
                    // Successfully got a response
                }
    
                @Override
                public void onFailure(Throwable e, String response) {
                    // Response failed :(
                }
    
                @Override
                public void onFinish() {
                    // Completed the request (either success or failure)
                }
            });
    }
    

    在上述回调中对您的活动中的视图做任何您需要做的事情。希望这会有所帮助!

    【讨论】:

    • 好的,感谢您的评论。所以正如你所说,我需要在我想要调用 Web 服务的任何活动中重复代码 onStart、onSuccess、onFailure、onFilish。正确的 ?假设在一个页面中,如果我需要 2-3 个电话,我想重复上述代码两次或三次。是吗?
    • 正确。我还要补充一点,您不必实现所有回调方法,只需实现您需要的那些。很多时候我只实现 onSuccess() 和 onFailure()。希望这会有所帮助,祝你好运!如果我的回答对您有所帮助,如果您将其作为正确答案进行检查,我将不胜感激。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多