How to Pass POJO class in Work manager in android?

10,337

Solution 1

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 !

Solution 2

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.

Share:
10,337
Vishal Patoliya ツ
Author by

Vishal Patoliya ツ

"Belive In work, not in words" I'm an android developer and i want to archive gratest knowledge in android development. ツ

Updated on June 09, 2022

Comments

  • Vishal Patoliya ツ
    Vishal Patoliya ツ about 2 years

    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.

  • Vishal Patoliya ツ
    Vishal Patoliya ツ almost 6 years
    Yeah we can do it but i from Db i fetch array and from arraylist i want to pass perticular pojo class and do process in work manager. Yea i already implemented this but if Work manager in direclty supports Serializable class than i want to check
  • Vishal Patoliya ツ
    Vishal Patoliya ツ over 5 years
    It will be create crash when you want to upload high resolution Image and second cons is like that you have to do more process like 1.Serialize into Json and 2. Deserialize into String to . JSON and it is very complex and risky process.
  • Yogesh Rathi
    Yogesh Rathi over 5 years
    agree, but its one of idea how to do this
  • Vishal Patoliya ツ
    Vishal Patoliya ツ over 5 years
    In short we have to pass String only in any ways.
  • Yogesh Rathi
    Yogesh Rathi over 5 years
    Yes dear. But if somehow we want to pass multiple strings so better to create pojo and do above operation.
  • TheRealChx101
    TheRealChx101 about 5 years
    And there's no way to pass other object instances as well because the data will be internally serialized/deserialized to and from a byte array using ObjectOutputStream and ObjectInputStream. Even though it's possible to write a serializable instance there, Google only allowed primitive types.
  • TheRealChx101
    TheRealChx101 about 5 years
    My architecture requires me to pass a shared instance to my static Worker to call some methods on that instance. I have no other option but to use a singleton; very ugly.