7

how to show toast in WorkManager do work()?

When I try, it throws

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
Nurseyit Tursunkulov
  • 8,012
  • 12
  • 44
  • 78

2 Answers2

25

You can create Handler to show Toast on UI thread.

Your doWork method will be like:

@NonNull
@Override
public Result doWork() {
    Log.d(TAG, "doWork for Sync");

    Handler handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // Run your task here
            Toast.makeText(mContext, "Testing", Toast.LENGTH_SHORT).show();
        }
    }, 1000 );

    return Result.success();
}

Note : mContext will be available in Constructor.

Hope it will help you. Thank you.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
  • the solution works well, but if you need to run it your work on background it will not. Because it requires context, so be aware! – Nurseyit Tursunkulov Jun 05 '19 at 03:34
  • 3
    @NurseyitTursunkulov Context is available inside workers via `getApplicationContext()` anyways so it will work regardless affinity. – VPZ Nov 13 '20 at 16:37
0

Also found alternative solution, worked for me as well:

@Override
public Result doWork() {
    context.getMainExecutor().execute(() -> Toast.makeText(context, "Сас ))", Toast.LENGTH_LONG).show());
    return Result.success();   // may be done with handler
}

But also i saved Context variable to the classfield

Context context;

public BackgroundWorker(Context context, WorkerParameters workerParams) {
    super(context, workerParams);
    this.context = context;
}
buba1219
  • 43
  • 2
  • 5