How to Pass POJO class in Work manager in android?

Vishal Patoliya ツ picture Vishal Patoliya ツ · Jun 25, 2018 · Viewed 7.4k times · Source

How can we pass Serializable object in work manager by setData method of work manager? Is there any way to process with Work manager by passing object?

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.

 Map<String, Object> map = new HashMap<>();
 AddressBookData addressBookData = new AddressBookData();
 addressBookData.setThreadId(001);

 map.put("AddressBookData", addressBookData);


 Data data = new Data.Builder()
                    .putAll(map)
                    .build();

 OneTimeWorkRequest compressionWork =
                new OneTimeWorkRequest.Builder(DataSyncWorker.class)
                        .setInputData(data)
                        .build();

It crash app and showing error like AddressBookData is not valid class.

Note: I want to pass POJO class in work manager and get InputData from work manager in doWork Method.

Answer

Martin Melka picture Martin Melka · Jul 4, 2018

You cannot directly provide a POJO for a WorkManager. See the documentation of the Data.Builder#putAll method:

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

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.

However, for more complicated classes, I personally store them in the database (SQLite, Room) and then just pass the primary key of the given object. The Worker then fetches the object from the database. However, in my experience that can be usually avoided.