-2
class BTCSync extends Thread{
        public void run(){
            while(!BTC && MainPage.BTC){
                TextView BTCPer = (TextView) findViewById(R.id.lblBTCPer);
                BTCPer.setText(BTCProgress+"%");
                if(BTCProgress == 100) {
                    BTCPer.setText("100%");
                    BTC = true;
                }
            }
        }
    }

The error is where findViewById my label is lblBTCPer.

The reason I have it in run() is that this block needs to run until the value hits 100.

I know that usually, you would have to throw in the View v but then it would negate the void run().

I looked for a few solutions but I haven't found a working example.

I also believe I posted this already just yesterday but I can't seem to find it anywhere. It's not under my account and I distinctly remember posting it and waiting for responses.

Onik
  • 19,396
  • 14
  • 68
  • 91
BTCDude
  • 31
  • 7

4 Answers4

1

findViewById() is a function of either Android Activity or View. Your BTCSync class does not extend neither of those.

Most likely Timertask or Handler would be a better fit for your requirement.

Onik
  • 19,396
  • 14
  • 68
  • 91
1

Aside from the findViewById problem, you're trying to do UI work on a non-UI thread. You'll need to use runOnUiThread() or you're going to get a crash:

    runOnUiThread(new Runnable() {
    @Override
    public void run() {
            BTCPer.setText(BTCProgress+"%");
            if(BTCProgress == 100) {
                BTCPer.setText("100%");
                BTC = true;
            }
    }
});
Gavin Wright
  • 3,124
  • 3
  • 14
  • 35
1

Android app have only one UI thread, and the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread.

In order to update ui in other thread, you could use handler, here is ref

and here is a good example

navylover
  • 12,383
  • 5
  • 28
  • 41
1

Android forbids altering the UI (for example setting a text of a textview) outside of the UI thread.

If you are able to call this line

TextView BTCPer = (TextView) findViewById(R.id.lblBTCPer);

then that means that your thread is defined inside your activity, because findViewById() is not a Thread's function. In this case:

class BTCSync extends Thread{
        public void run(){
            while(!BTC && MainPage.BTC){
                TextView BTCPer = (TextView) findViewById(R.id.lblBTCPer);
                // make sure you enable lambdas
                runOnUiThread(() -> BTCPer.setText(BTCProgress+"%"));
                if(BTCProgress == 100) {
                    BTCPer.setText("100%");
                    BTC = true;
                }
            }
        }
Themelis
  • 4,048
  • 2
  • 21
  • 45