Asynchttpclient for Android loopj feedback

In one of my projects, I use loopj asynchttpclient to communicate with my site. The communication part works well and gets a 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 answer to the main action so that I can create a list from this answer.

I'm new to this please help me Thanks in advance

+7
android android-layout web-services android-asynctask loopj
source share
1 answer

In your WebRequest class:

  • I don’t think you want this class to extend the Activity . You should only expand Activity when you create a page to display in your application. You just want to execute some code, so an Activity extension is not required.
  • Change your call service method as static and take AsyncHttpClient as the parameter.

Your WebRequest 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 business:

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

 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 everything you need to do with the representations in your activity in the above callbacks. Hope this helps!

+7
source

All Articles