How to Pass POJO class in Work manager in android?

前端 未结 2 2124
没有蜡笔的小新
没有蜡笔的小新 2021-02-19 03:21

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

2条回答
  •  清酒与你
    2021-02-19 03:50

    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 !

提交回复
热议问题