1

I did some research and tried some code including the code below from Android postDelayed Handler Inside a For Loop?.

final Handler handler = new Handler(); 


    int count = 0;
    final Runnable runnable = new Runnable() {
        public void run() { 

            // need to do tasks on the UI thread 
            Log.d(TAG, "runn test");


            if (count++ < 5)
                handler.postDelayed(this, 5000);

        } 
    }; 

    // trigger first time 
    handler.post(runnable);

But the count variable will show an error because it is accessed within the inner class. How can I solve the problem?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
unityx1
  • 27
  • 4

1 Answers1

0

Variable 'count' is accessed from within inner class, needs to be final or effectively final

you need to Transform count into final One element array

final Handler handler = new Handler();

final int[] count = {0};        //<--changed here
final Runnable runnable = new Runnable() {
    public void run() {

        // need to do tasks on the UI thread
        Log.d(TAG, "runn test");


        if (count[0]++ < 5)     //<--changed here
            handler.postDelayed(this, 5000);

    }
};

// trigger first time
handler.post(runnable);
Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
Nikunj Paradva
  • 15,332
  • 5
  • 54
  • 65