Skip to content

Instantly share code, notes, and snippets.

@adriantache
Last active September 28, 2018 14:20
Show Gist options
  • Save adriantache/ebc8303bd2308440e30de6875c69b984 to your computer and use it in GitHub Desktop.
Save adriantache/ebc8303bd2308440e30de6875c69b984 to your computer and use it in GitHub Desktop.
//we create a class that extends Worker
public class UpdateEventsWorker extends Worker {
//here we define the constants for the remote URL LiveData tag and
//the filename of the file we'll be exporting the JSON to
private static final String REMOTE_URL = "REMOTE_URL";
private static final String JSON_RESULT = "JSON_STRING";
public UpdateEventsWorker(@NonNull Context context, @NonNull WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
//firstly, we get the livedata and store it in a String
Data input = getInputData();
final String remoteUrl = input.getString(REMOTE_URL);
//then we try to fetch the remote JSON file and store it into a String
String jsonString = null;
try {
jsonString = getJSON(remoteUrl);
} catch (IOException e) {
e.printStackTrace();
}
//if this succeeds, we store it in a file since LiveData is limited
//to 10KB for some reason; I'm using a PrintWriter instead of just
//accessing the FileInputStream directly since I need the UTF-8 encoding
if (!TextUtils.isEmpty(jsonString) && jsonString.length() > 50) {
try(PrintWriter printWriter = new PrintWriter(new File(getApplicationContext()
.getFilesDir(), JSON_RESULT), "UTF-8")){
printWriter.write(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
//we return SUCCESS if all is well
return Result.SUCCESS;
}
//otherwise we return FAILURE so we know something went wrong
else return Result.FAILURE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment