Search code examples
androidweb-servicesandroid-layoutandroid-asynctaskloopj

Android loopj asynchttpclient return response


In one of my project, I am using loopj asynchttpclient for communicating with my website. The communication part working well and getting response as well

My activity looks like

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

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

WebRequest Class as

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

    });
    }




}

I am confused how to return the response to the main activity, So that I can create the listview from that response.

I am new to this Please help me Thanks in advance


Solution

  • In your WebRequest class:

    • I don't think you want this class to extend Activity. You should only extend Activity when you're making a page to display in your app. You just want to execute some code, so extending Activity isn't needed.
    • Change your call service method to be static and take an AsyncHttpClient as a parameter.

    Your WebRequest class should now look like this:

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

    In your main Activity:

    Now all you have to do in your main activity is call the static method like this:

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

    Do whatever you need to do with the Views in your activity in the above callbacks. Hope this Helps!