Skip to content
Emir Hasanbegovic edited this page Aug 23, 2014 · 6 revisions

Step 1: Json

SampleResponse.java

public class SampleJsonResponse {

    @SerializedName(Fields.RESULT)
    public ArrayList<SampleJsonModel> mSampleJsonModels;

    public static class Fields {
        public static final String RESULT = "result";
    }
}

Step 2: Task

SampleTask.java

public class SampleTask extends Task {

    private static final String SCHEME = "http";
    private static final String API_AUTHORITY = "api.com";
    public static final String path = "path";

    public SampleTask(final Context context, final String authorty, final Uri uri) {
        super(context, authorty, uri);
    }

    @Override
    protected void onExecuteTask(final Context context) throws Exception {

        // NETWORK REQUEST
        final Uri networkUri = SampleUriUtilities.getUri(SCHEME, API_AUTHORITY, Paths.Path);
        final String url = networkUri.toString();
        final SampleJsonResponse sampleJsonResponse = TaskUtilities.getModel(url, SampleJsonResponse.class);

        // DELETE OLD CONTENT
        final Uri modelUri = SampleUriUtilities.getUri(context, SampleModel.Paths.PATH);
        final ArrayList<ContentProviderOperation> contentProviderOperations = new ArrayList<ContentProviderOperation>();
        final ContentProviderOperation deleteContentProviderOperation = ContentProviderOperation.newDelete(modelUri).build();
        contentProviderOperations.add(deleteContentProviderOperation);

        // WRITE DATA TO DATABASE
        final ArrayList<SampleJsonModel> sampleJsonModels = sampleJsonResponse.mSampleJsonModels;
        for (final SampleJsonModel sampleJsonModel : sampleJsonModels) {
            final ContentValues contentValues = SampleModelModel.getContentValues(sampleJsonModel);
            final ContentProviderOperation insertContentProviderOperation = ContentProviderOperation.newInsert(modelUri).withValues(contentValues).build();
            contentProviderOperations.add(insertContentProviderOperation);
        }

        final Resources resources = context.getResources();
        final String authority = resources.getString(R.string.authority);

        // APPLY DATABASE TRANSACTIONS ATOMICALLY
        final ContentResolver contentResolver = context.getContentResolver();
        contentResolver.applyBatch(authority, contentProviderOperations);

        // NOTIFY BINDINGS THAT SampleViewModel'S UNDERLYING DATA HAS CHANGED
        final Uri sampleViewModelUri = SampleUriUtilities.getUri(context, SampleViewModel.Paths.PATH);
        contentResolver.notifyChange(sampleViewModelUri, null);
    }

    @PathDefinitions
    public static class Paths {
        @PathDefinition
        public static final Path PATH = new Path(SampleTask.class.getName());
    }
}

Step 3 (Optional): Task Utilities

A simple way of doing a GET request.

TaskUtilities.java

public class TaskUtilities {
    private static final Gson GSON = new Gson();

    public static <RESPONSE_CLASS> RESPONSE_CLASS getModel(final String url, final Class<RESPONSE_CLASS> responseClass) {
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        try {
            final HttpClient httpclient = new DefaultHttpClient();

            final HttpGet httpGet = new HttpGet();
            final URI uri = new URI(url);
            httpGet.setURI(uri);
            HttpResponse httpResponse = httpclient.execute(httpGet);
            inputStream = httpResponse.getEntity().getContent();
            inputStreamReader = new InputStreamReader(inputStream);
            return GSON.fromJson(inputStreamReader, responseClass);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }
}

Step 4: Register Tasks with the TaskService

SampleTaskService.java

 @Override
    public Set<Class> getTasks(final Context context) {
        final Set<Class> tasks = new HashSet<Class>();

        tasks.add(SampleTask.class);

        return tasks;
    }

Step 5: Starting Tasks

This goes where you feel it is important to refresh the data. We recommend either onStart of the Fragment or Activity that needs the data, or in the query method for the ViewModel that this task corresponds to.

final Uri uri = SampleProvider.getUri(context, SampleTask.Paths.PATH);
SampleTaskService.startTask(this, uri);

SampleTaskService.startTask(Context, Uri) ensures that we don't run more than one task every thirty seconds, by default. This can be modified by changing the return values of getUpdateTime() or needsUpdate(Cursor) to suit your needs. But if you need to force a request use SampleTaskService.forceStartTask(Context, Uri). It is ideal for a refresh button or a pull to refresh.