Ongoin use of variable in Worker class Android

121 views Asked by At

Im trying to perform a one time work with the worker class where the doWork method will just count a number Call it I. This will loop through 100 times, and in every iteration, the counter will continue grow up.

I added a constraint for this work to be network Constraining connected.

I would like to count every time and if I close the Network the count will stop. After I open the network I would like The count to continue work from the same count value that was there before

Every time I close the network and open it again the count starts from zero again and the value that was in the counter before didn't save in the global variable I that I defined in the worker. it's like not taking the last value that was defined there.

My worker class

class WorkerClass(appContext: Context, workerParams: WorkerParameters):
    Worker(appContext, workerParams) {
    var i:Int=0
     override fun doWork(): Result {

         while (i < 100) {
             if (this.isStopped){
                 Log.i("Hello","I Stopped A")
                     return Result.retry()
             }
             i++
             Log.i("Hello", "The value of counter is :"+i.toString())
             Thread.sleep(200)
         }
        return Result.success()
     }
}

My simple work creator: (There is a data passed I don't use it right now so you can ignore it.

 val constrints=Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()

        val k = sceondTxt.text.toString()
        val data=Data.Builder()
        data.putString("Counter Value",k)
        val oneReq:WorkRequest= OneTimeWorkRequestBuilder<WorkerClass>().setConstraints(constrints).setInputData(data.build())
            .build()

So as you can see I define an I as Integer and every iteration of the work the I is growing. but when I close the connection and open it again the I is 0 again and didn't save from the last run of doWork.

does the definition of i is not global? the system wont take the last value of I that was stored in the doWork for later iterations?

How can I save the value of something in my doWork to later use it again (after the constraints are met) not as the default value?

0

There are 0 answers