Best Practice for HTTP Request in Activity

98 views
Skip to first unread message

joey mason

unread,
Sep 3, 2014, 1:56:50 AM9/3/14
to android-...@googlegroups.com
I'd like to make an HTTP POST request when a button is clicked. Initially, I made my Activity implement OnClickListener. However, while handling the click event, when I attempted to retrieve the service using BootstrapServiceProvider.getService(), an exception was thrown because the call was happening on the main UI thread. To get around this, it seems like there a few options:

- Use the event bus
- Put the button in a fragment

Has anyone come across this? What is the best strategy here?  

Donn Felker

unread,
Sep 3, 2014, 1:59:42 PM9/3/14
to android-...@googlegroups.com

Use an AsycTask

joey mason

unread,
Sep 3, 2014, 9:10:03 PM9/3/14
to android-...@googlegroups.com, do...@donnfelker.com
That seems simple enough, but to retrieve a service from BootstrapServiceProvider, you need to provide an activity, so it seems like this could get a little messy. Or will that not be an issue?

On Wednesday, September 3, 2014 10:59:42 AM UTC-7, Donn Felker wrote:

Use an AsycTask

joey mason

unread,
Sep 3, 2014, 10:13:37 PM9/3/14
to android-...@googlegroups.com, do...@donnfelker.com
Here's an example of what I'm doing:

public class MyActivity extends BootstrapActivity implements View.OnClickListener {
 
   @Inject protected BootstrapServiceProvider serviceProvider;
   // .........

   @Override
   public void onClick(final View v) {
      // ......
      new CreateArticleAsyncTask().doInBackground(article);
   }

   private
class CreateArticleAsyncTask extends AsyncTask<Article, Void, Void> {
        @Override
        protected Void doInBackground(Redemption... params) {
            for (Article article : params) {
                try {
                    serviceProvider.getService(getParent()).createArticle(article);
                } catch (Exception e) {
                    Ln.e(e, "Unable to create article");
                }
            }

            return null;
        }
   }
}



This is the error message I'm getting:

09-03 19:06:04.297  11253-11253/com.foobar.android.debug E/AccountManager﹕ calling this from your main thread can lead to deadlock and/or ANRs
    java.lang.IllegalStateException: calling this from your main thread can lead to deadlock
......
at com.foobar.android.authenticator.ApiKeyProvider.getAuthKey(ApiKeyProvider.java:51)
            at com.foobar.android.BootstrapServiceProvider.getService(BootstrapServiceProvider.java:42)


It seems to be failing because of the reference to the parent activity, but I'm not sure how else to retrieve the Service I need to make the POST request. There must be a better way to do this.
Reply all
Reply to author
Forward
0 new messages