How To Pass Pojo Class In Work Manager In Android?
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.publicstaticStringserializeToJson(Bitmap bmp) {
Gson gson = newGson();
return gson.toJson(bmp);
}
// Deserialize to single object.publicstaticBitmapdeserializeFromJson(String jsonString) {
Gson gson = newGson();
return gson.fromJson(jsonString, Bitmap.class);
}
Serialize object.
StringbitmapString= 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.
Datadata= getInputData();
StringbitmapString= data.getString(NOTIFICATION_BITMAP);
Bitmapbitmap= 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.
Post a Comment for "How To Pass Pojo Class In Work Manager In Android?"