Search code examples
androidasynchronousmobileworkerandroid-workmanager

Android: Change TextView via async Worker class


I am trying to attempt async programming in android by using the WorkManager and Worker classes by getting a worker to change the view of the MainActivity (instead of doing it on the MainActivity itself). Here is my code for MainActivity:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        val myWorkRequest: WorkRequest =
            OneTimeWorkRequestBuilder<myWorker>()
                .build()

        WorkManager
            .getInstance(this)
            .enqueue(myWorkRequest)


    }

And this is the code for my Worker class:

class myWorker(appContext: Context, workerParams: WorkerParameters, mainView: View): Worker(appContext, workerParams) {
    private val ctx = appContext
    private val view = mainView
    override fun doWork(): Result {
        // Do the work here
        myWork()

        // Indicate whether the work finished successfully with the Result
        return Result.success()

    }
    fun myWork(): Boolean{
        val textView2: TextView = view.findViewById(R.id.textView2)
        textView2.setText("TEST!")
        return true;
    }
}

I am pretty sure the problem lies in the passing of parameters into myWorker, and I don't quite understand how and what exactly I should be passing into the Worker class in order to make it affect the MainActivity.


Solution

  • You do not pass View to a Worker Class . Never! . This can cause certain problems like NPE and Memory leaks ..

    Now coming to second problem You do not use WorkManager for async programming Normally . WorkManager is more suited for scheduled task something you want to do in future and it might be deferred . That's more often called background task(basically when app is not opened) . Have look at This and This thread .

    If you want some async Operation to do you have basically two widely used options Coroutines and Rxjava . Since you are already using kotlin you can go with Coroutines and also fact that its easy to implement.

    Now in such where you want to provide a callback to a UI component from a Worker you can follow This .

    Normally if your async task is an immediate one you do not use Worker you use a Thread in this case . Coroutines is a multi threading framework so u can go for it .