Marco Jacobo
Marco Jacobo

Reputation: 31

How to force progressbar get visible just before a background thread starts its execution?

I think this is a very simple question for many people in this community, however, I can't make this to work after several experiments; I would appreciate any help.

It is JAVA-android platform: The code needs to execute the next steps when the user clicks a button:

  1. Make invisible the button (run in main thread)

  2. Make visible a progress bar (run in main thread)

  3. Download a file from internet (run in background thread)

  4. Wait the download is completed

  5. Make invisible the progress bar

  6. Make visible again the button

That's it. It doesn't seem to be very difficult, however, it is not working as I need it.

This is the issue: Step 3 get executed before steps 1 and 2, ... I have tried several experiments with not success.

private void f1()
{
    mDataBinding.btnPausePlay.setVisibility(btnVisibility);                    
    mDataBinding.progressPausePlay.setVisibility(progressVisibility);
}

private void f2()
{
        Thread xThread = new Thread( new Runnable()
        {   @Override
            public void run()                            // run in background thread
            { httpRequest_noBackgroundThread( urlStr, urlParams, fileStr, itf );  }
        });
        try
        {
            xThread.start();
            xThread.join();     // wait for the thread to finish
        }
           catch( Exception e ){   e.printStackTrace();  }
}


private void f3()
{
        f1();
        f2();
       // continues execution ...
}

###########################################################

Based on Shagun Verma's feedback; It was the fix for my specific issue. Thank you!

private void f3()
{
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.execute(() ->
    {       
        f1();
        f2();
       // continues execution ...

    });
}

Upvotes: 0

Views: 105

Answers (1)

Android Coder
Android Coder

Reputation: 163

To accomplish this, you have to use Executors in Java. The below code will be done the job for you-

btnPausePlay.setOnClickListener(view -> {
    btnPausePlay.setVisibility(View.GONE);
    progressPausePlay.setVisibility(View.VISIBLE);
    ExecutorService executorService =  Executors.newSingleThreadExecutor();
        executorService.execute(() -> {
            // Implement your file download code here i.e.
            // httpRequest_noBackgroundThread( urlStr, urlParams, fileStr, itf );
        handler.post(() -> {
            btnPausePlay.setVisibility(View.VISIBLE);
            progressPausePlay.setVisibility(View.GONE);
        });
    });
});

When you press the btnPausePlay button, then it will become invisible and the progress bar becomes visible. After that, once the download is completed reverse will happen.

Upvotes: 1

Related Questions