Android loopj asynchttpclient返回响应

ram*_*esh 7 android web-services android-layout android-asynctask loopj

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

我的活动看起来像

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

        WebRequest test=new WebRequest();
        test.callService();
}
Run Code Online (Sandbox Code Playgroud)

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());
            }

    });
    }




}
Run Code Online (Sandbox Code Playgroud)

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

我是新来的请帮助我提前谢谢

aha*_*ing 7

在您的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的主要活动中:

现在,您在主要活动中所要做的就是调用静态方法,如下所示:

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)
            }
        });
}
Run Code Online (Sandbox Code Playgroud)

在上述回调中,您需要对活动中的视图执行任何操作.希望这可以帮助!