user3121585
user3121585

Reputation: 1

Trying to decide which method to use for Android connecting to web service

I have read several articles on this site, and several books about Handlers, Threads, HandlerThreads, Services, SyncAdapters, ContentProviders and on and on. There seems like a lot of different options and I don't know which is appropriate for my project.

I have a simple project that will connect to a simple REST web service when the app starts for the very first time. It will download some JSON data and show this in a list. The user may then edit this data, and after hitting "save" the app will send a POST to the web service with the updated data. The user may also instigate a "sync" manually which will check for any new data. Finally, the app should check the web service periodically to see if there's more data.

I started with a Content Provider but it seemed really overkill (and complicated) tho I'm sure it would eventually work. I then tried a Thread, but Android suggests using AsyncTask or Handlers instead. I have been playing around with them (putting them in a service), and both will do what I want (using a timer to initiate a sync every X minutes) but I don't know if this is the best way of handling this. I am worried because this project may grow to incorporate much more, and I don't want to choose an option that will limit me in the future, but I also don't want to invest tons of hours into something that's overkill.

Can anyone help?

Upvotes: 0

Views: 40

Answers (1)

Greg Giacovelli
Greg Giacovelli

Reputation: 10184

Let's just start with what that whole keep it simple paradigm.

AsyncTask would be something like this:

public class MyAsyncTask extends AsyncTask<Void, Void, Data> {

   public interface OnDone {
      public void onDone(Data data);
   }

   private final OnDone mDone;

   public MyAsyncTask(OnDone onDone) {
      mDone = onDone;
   }

   public Data doInBackground(Void v) {
      // Download and parse your JSON in the background
   }

   public void onPostExecute(Data data) {
        mOnDone.onDone(data);
   }

}

public class OnDoneImpl .... implements OnDone, Runnable {

    ...
    // Just need a context in scope some how, an activity, the application whatever.
    Context mContext;

    public void onDone(Data data) {
        updateList(data);
        scheduleAgainInXMinutes(TIME_TILL_REFRESH);
    }

    public void scheduleAgainInXMinutes(long millis) {
        // probably want to use an Alarm service but can always use a handler;
        new Handler().postDelayed(this, millis);   
    }

    public void run() {
          new MyAsyncTask(this).execute();
    }
}

Upvotes: 1

Related Questions