'How can I parse JSON data from URL in a background thread in Android (Preferably using Work Manager)?
I've tried many different solutions such as using asyncTask and Work Manager but I can't seem to be able to transfer the parsed data from the background thread to my activity/class. I even tried working around it by attempting to write the parsed string into SharedPreferences, but I wasn't able to do it in the background thread method. Whenever I attempt to get the parsed string from my activity, it always returns a null string. I've fallen way behind schedule and am at a loss on what to do, I'll just post the request and the code for my current Work Manager request, I would greatly appreciate it if someone could help me out with this:
String taskJSON;
WorkRequest ReadWorkRequest =
new OneTimeWorkRequest.Builder(ReadWorker.class)
.build();
WorkManager
.getInstance(this)
.enqueue(ReadWorkRequest);
WorkManager.getInstance(this).getWorkInfoByIdLiveData(ReadWorkRequest.getId())
.observe(this, info -> {
if (info != null && info.getState().isFinished()) {
String myResult = info.getOutputData().getString("tasks:");
taskJSON=myResult;
}
});
Above is the work manager request and here's the class:
public class ReadWorker extends Worker {
public ReadWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
}
@Override
public Result doWork() {
ArrayList<Task> taskList = new ArrayList<>();
Data output = null;
String json = "";
String readTasksURL = "http://10.0.2.2/BD2/tasks/read";
try {
json = readUrl(readTasksURL);
Gson gson = new Gson();
Task object = gson.fromJson(json, Task.class);
taskList.add(object);
output = new Data.Builder().putString("tasks:",json).build();
} catch (Exception e) {
e.printStackTrace();
}
// Indicate whether the work finished successfully with the Result
return Result.success(output);
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
String test = "";
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
test = buffer.toString();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return test;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
