How to update Room Database using Android WorkManager

In this android programming source code example, we are going to update Room Database using Android WorkManager.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to update Room Database using Android WorkManager.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"    tools:context=".WorkManagerAndJobSchedule.WorkManagerAndJobScheduleActivity11">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp">

        <TextView
            android:id="@+id/tvdata"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Empty Data..."
            android:textColor="#000000"
            android:textSize="19sp"/>

        <Button
            android:id="@+id/schedule"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:text="Schedule Work"
            android:textAllCaps="false"
            android:textColor="#ffffff"
            android:textSize="19sp"
            android:layout_marginTop="10dp"/>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


import java.util.List;
import java.util.concurrent.TimeUnit;

public class WorkManagerAndJobScheduleActivity11 extends AppCompatActivity {
    private TextView tvdata;
    private Button schedule;
    private DataDatabase dataDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_manager_and_job_schedule11);
        tvdata = (TextView) findViewById(R.id.tvdata);
        schedule = (Button) findViewById(R.id.schedule);
        dataDatabase = DataDatabase.getInstance(this);
        readData();
        schedule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startWork();
            }
        });
    }

    private void readData(){
        dataDatabase.dataDAO().getlimituserList().observe(this, new Observer<List<WorkData11>>() {
            @Override
            public void onChanged(@Nullable List<WorkData11> data) {
                for(int i = 0; i<data.size(); i++){
                    tvdata.setText(data.get(i).getData());
                }
            }
        });
    }

    private void startWork(){
        OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(WorkManager11.class)
                .setInputData(createInputData("Inducesmile","Hello world, work completed on time"))
                .setInitialDelay(3, TimeUnit.SECONDS).build();
        WorkManager.getInstance(this).enqueue(oneTimeWorkRequest);
    }

    private Data createInputData(String title, String message){
        Data data = new Data.Builder()
                .putString("title", title)
                .putString("message", message)
                .build();
        return data;
    }
}

DataDatabase.java

import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

@Database(entities = { WorkData11.class }, version = 1, exportSchema = false)
public abstract class DataDatabase extends RoomDatabase {
    private static final String DB_NAME ="DataDb";
    private static DataDatabase instance;
    public abstract DataDAO dataDAO();

    public synchronized static DataDatabase getInstance(final Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context, DataDatabase.class, DB_NAME)
                    .allowMainThreadQueries().build();
        }
        return instance;
    }
}

WorkData11.java

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;

@Entity(tableName = "datas")
public class WorkData11 {
    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "data")
    private String data;

    public WorkData11(int id, String data){
        this.id = id;
        this.data = data;
    }

    @Ignore
    public WorkData11(String data){
        this.data = data;
    }
    public int getId() {
        return id;
    }
    public String getData() {
        return data;
    }
}

DataDAO.java

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;

@Dao
public interface DataDAO {

    @Insert
    public void insert(WorkData11 workData11);

    @Update
    public void update(WorkData11 workData11);

    @Delete
    public void delete(WorkData11 workData11);

    @Query("select * from datas limit 1")
    LiveData<List<WorkData11>> getlimituserList();

}

WorkManager11.java

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import io.reactivex.Completable;
import io.reactivex.CompletableObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;


public class WorkManager11 extends Worker {
    private DataDatabase dataDatabase;

    public WorkManager11(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        dataDatabase = DataDatabase.getInstance(getApplicationContext());
    }

    @NonNull
    @Override
    public Result doWork() {
        String title = getInputData().getString("title");
        String message = getInputData().getString("message");
        String data = "Title: "+title+" Message: "+message;
        saveData(data);
        return Result.success();
    }

    private void saveData(final String data){
        Completable.fromAction(new Action() {
            @Override
            public void run() throws Exception {
                WorkData11 workdata = new WorkData11(data);
                dataDatabase.dataDAO().insert(workdata);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CompletableObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onComplete() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }

}

app/build.gradle

implementation 'androidx.work:work-runtime:2.1.0-beta02'
implementation 'androidx.room:room-runtime:2.1.0'
implementation 'androidx.room:room-rxjava2:2.1.0'
implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
annotationProcessor 'androidx.room:room-compiler:2.1.0'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment