Vishal Patoliya ツ
Vishal Patoliya ツ

Reputation: 3238

How to pass own class into Worker in android?

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.

Upvotes: 25

Views: 15974

Answers (3)

Aada
Aada

Reputation: 1640

WorkManager allows only these types - Byte, Integer, Long, Boolean,Double , String, Float and array of these types. Otherwise it will throw IllegalArgumentException This is the internal implementation of Data class -

if (value == null) {
                mValues.put(key, null);
            } else {
                Class<?> valueType = value.getClass();
                if (valueType == Boolean.class
                        || valueType == Byte.class
                        || valueType == Integer.class
                        || valueType == Long.class
                        || valueType == Float.class
                        || valueType == Double.class
                        || valueType == String.class
                        || valueType == Boolean[].class
                        || valueType == Byte[].class
                        || valueType == Integer[].class
                        || valueType == Long[].class
                        || valueType == Float[].class
                        || valueType == Double[].class
                        || valueType == String[].class) {
                    mValues.put(key, value);
                } else if (valueType == boolean[].class) {
                    mValues.put(key, convertPrimitiveBooleanArray((boolean[]) value));
                } else if (valueType == byte[].class) {
                    mValues.put(key, convertPrimitiveByteArray((byte[]) value));
                } else if (valueType == int[].class) {
                    mValues.put(key, convertPrimitiveIntArray((int[]) value));
                } else if (valueType == long[].class) {
                    mValues.put(key, convertPrimitiveLongArray((long[]) value));
                } else if (valueType == float[].class) {
                    mValues.put(key, convertPrimitiveFloatArray((float[]) value));
                } else if (valueType == double[].class) {
                    mValues.put(key, convertPrimitiveDoubleArray((double[]) value));
                } else {
                    throw new IllegalArgumentException(
                            String.format("Key %s has invalid type %s", key, valueType));
                }

Upvotes: 0

Yogesh Rathi
Yogesh Rathi

Reputation: 6499

Today, I also faced this issue. So I found the way to pass an object.

My Requirement is pass Bitmap object. (You can pass as per your requirement)

Add dependency in your Gradle file

Gradle:

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

Use the below method for serializing and de-serializing the object

 // Serialize a single object.
    public static String serializeToJson(Bitmap bmp) {
        Gson gson = new Gson();
        return gson.toJson(bmp);
    }

    // Deserialize to single object.
    public static Bitmap deserializeFromJson(String jsonString) {
        Gson gson = new Gson();
        return gson.fromJson(jsonString, Bitmap.class);
    }

Serialize object.

 String bitmapString = Helper.serializeToJson(bmp);

Pass to the data object.

 Data.Builder builder = new Data.Builder();
 builder.putString("bmp, bitmapString);
 Data data = builder.build();
        OneTimeWorkRequest simpleRequest = new OneTimeWorkRequest.Builder(ExampleWorker.class)
                .setInputData(data)
                .build();
        WorkManager.getInstance().enqueue(simpleRequest);

Handle your value in Worker class.

Data data = getInputData();
String bitmapString = data.getString(NOTIFICATION_BITMAP);
Bitmap bitmap = Helper.deserializeFromJson(bitmapString);

Now your bitmap object is ready in Worker class.

Cheers !

Upvotes: 16

Martin Melka
Martin Melka

Reputation: 7789

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.

Upvotes: 9

Related Questions