简体   繁体   中英

Variable is accessed from within inner class

I have these varibles:

private boolean MineRunning;
private BigInteger MineProfit;
etc....

I want to call the countdown method:

countdown(MineRunning, MineProfit, MineTime, MineProgressbar, MineProgressstatus);

ca. 10 Times for different things

The method:

private void countdown(boolean running,  BigInteger profit, BigInteger time,  ProgressBar progressBar, int progressStatus) {
    if(!running && Reference.Storage_Filled.add(profit).compareTo(Reference.Storage_Capacity) == 0 ||
            !running && Reference.Storage_Filled.add(profit).compareTo(Reference.Storage_Capacity) == -1){
        running = true;

        new CountDownTimer(time.longValue(), Reference.countDownInterval.longValue()){
            public void onTick(long millisUntilFinished){
                progressStatus++;
                progressBar.setProgress(progressStatus);
            }

            public void onFinish(){

                Reference.totalGravel = Reference.totalGravel.add(profit);
                Gravelrefresh();

                progressStatus = 0;
                progressBar.setProgress(progressStatus);

                running = false;
            }
        }.start();

    }
}

If I call this method i get an error:

variable is accessed from within inner class

I dont want to make the varibles to final because I have to edit these in the method. What can I do instead? Thanks.

If your inner class is performing work on a separate thread, which seems to be the case here, you cannot access variables from this inner class. What you can do however, you can pass these variables as parameters to your inner class constructor, create new variables, copy them and manipulate.

Or you just declare them as final, that's not a problem most of the time.

Any variable accessed by an inner class must either be final or be a class scoped variable. There is no way around that. Either don't update those variables, or follow the rules.

Adding final normally isn't a problem. Final doesn't prevent you from mutating an object, it just prevents you from assigning to the reference. You can still call a function like setProgress that changes its internal state.

What if you make those variables static

private static boolean MineRunning;
private static BigInteger MineProfit;
...

And make your method parameter less

private void countdown(){ 
    //Your code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM