When you have a big POJO with loads of variables (Booleans, Int, Strings) and you want to use the new Work Manager to start a job. You then create a Data file which gets added t
Accepted answer is correct. But new android developer can not understand easily, So thats why i given another answer with proper explanation.
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 below method for serialize and de-serialize 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 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 object in your
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.
Above is example, how to pass object in your worker class.