Task
- Step 1: Json
- Step 2: Task
- Step 3 (Optional): Task utilities
- Step 4: Register Tasks with the TaskService
- Step 5: Starting Tasks
public class SampleJsonResponse {
@SerializedName(Fields.RESULT)
public ArrayList<SampleJsonModel> mSampleJsonModels;
public static class Fields {
public static final String RESULT = "result";
}
}
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());
}
}
A simple way of doing a GET request.
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;
}
}
@Override
public Set<Class> getTasks(final Context context) {
final Set<Class> tasks = new HashSet<Class>();
tasks.add(SampleTask.class);
return 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.
Copyright 2014 Emir Hasanbegovic
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.