Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Complex Types of Objects to WorkManager in android. i.e lists, maps, POJO

WorkManager is a library used to enqueue work that is guaranteed to execute after its constraints are met. WorkManager allows observation of work status and the ability to create complex chains of work.

Valid types supported are only: Boolean, Integer, Long, Double, String, and array versions of each of those types.

// Define the Worker class:
public class MathWorker extends Worker {

    // Define the parameter keys:
    public static final String KEY_X_ARG = "X";
    public static final String KEY_Y_ARG = "Y";
    public static final String KEY_Z_ARG = "Z";
    // ...and the result key:
    public static final String KEY_RESULT = "result";

    public MathWorker(
        @NonNull Context context,
        @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Worker.Result doWork() {
        // Fetch the arguments (and specify default values):
        int x = getInputData().getInt(KEY_X_ARG, 0);
        int y = getInputData().getInt(KEY_Y_ARG, 0);
        int z = getInputData().getInt(KEY_Z_ARG, 0);

        // ...do the math...
        int result = myCrazyMathFunction(x, y, z);

        //...set the output, and we're done!
        Data output = new Data.Builder()
            .putInt(KEY_RESULT, result)
            .build();
        setOutputData(output);
        return Result.SUCCESS;
    }
}

How can i pass complex types like:

Map<String, Object> studListMap = new HashMap<>();
        studListMap.put("list", studentDetails);

        // Create the Data object:
        @SuppressLint("RestrictedApi")
        Data myData = new Data.Builder()
                .put(KEY_STUD_LIST_ARG,studListMap)
                .build();

        //set network required
        Constraints myConstraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build();
like image 483
Job M Avatar asked Nov 06 '18 12:11

Job M


People also ask

What is the use of workmanager in Android?

WorkManager is intended for tasks that are deferrable — that is, not required to run immediately — and required to run reliably even if the app exits or the device restarts. For example: Backing up user data with Server on a Periodic basis (Eg: WhatsApp, Google, etc.,)

What are the constraints available with Android workmanager?

There are many other constraints available with Android WorkManager including ‘requires charging’, ‘storage is not low’, ‘device is not idle’, etc. A list of all these constraints can be found below:

How to send user data to the server in Android workmanager?

Like in our example, if we want to send user data to the server via a Worker, we need to pass that user data to the Worker task. In Android WorkManager, we can do so by using the Data class. The input data is nothing but a list of key-value pairs.

How to pass multiple onetimeworkrequest objects to the workmanager?

The WorkManagerruns the tasks in the requested order, according to each task's specified constraints. If any task returns Result.failure(), the whole sequence ends. You can also pass multiple OneTimeWorkRequestobjects to any of the beginWith(List<OneTimeWorkRequest>)and then(List<OneTimeWorkRequest>)calls.


1 Answers

If possible, you may serialize your POJO. For example, if it is truly small and simple, you can use JSON to encode it to string and then decode it in the Worker.

Have used gson, since it's already a dependency in this app.

 Map<String, Object> studListMap = new HashMap<>();
        studListMap.put("list", studentDetails);

        Type listOfStudObject = new TypeToken<List<StudentDetails>>(){}.getType();
        String s = gson.toJson(studentDetails, listOfStudObject);

        // Create the Data object:
        @SuppressLint("RestrictedApi")
        Data myData = new Data.Builder()
                .putString(KEY_STUD_LIST_ARG,s)
                .build();

        //set network required
        Constraints myConstraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build();

        // ...then create and enqueue a OneTimeWorkRequest that uses those arguments
        OneTimeWorkRequest attendWork = new OneTimeWorkRequest.Builder(AddAttendanceWorker.class)
                .setConstraints(myConstraints)
                .setInputData(myData)
                .build();

        WorkManager.getInstance()
                .enqueue(attendWork);
like image 90
Job M Avatar answered Nov 14 '22 23:11

Job M