-1

i have a function

protected void updateLogs()

in my activity (MainActivity).

I need to call this function with delay. I cann't use this method https://stackoverflow.com/a/9166354/3883330 because i can't call function from other class, because it's not static function. Code with error:

final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    MainActivity.updateLogs();
                }
            }, 100);

How can i solve this?

Community
  • 1
  • 1
fiction
  • 566
  • 1
  • 6
  • 21

1 Answers1

1

This should work:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        updateLogs();
    }
}, 100);

If it doesn't, declare a final object containing this:

final MainActivity main = this; // Just need to make it final
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        main.updateLogs();
    }
}, 100);

As Carnal pointed out, it would be cleaner to declare an interface making the method to call public, however since you're calling it from an inner class, I think it's OK that way.

Community
  • 1
  • 1
Siguza
  • 21,155
  • 6
  • 52
  • 89