-3

I have the following code:

private static AppWidgetService mInstance = null;

public static void startRefresh() {

        AppWidgetProvider.setRefreshingState(mInstance
                .getApplicationContext());
        AppWidgetManager.refreshHandler(mInstance.getApplicationContext());
    }

It sometimes fails in runtime, and sometimes passes.

for the obviuse exception:

cannot call a non-static method from a static context

I'm confused as mInstance is static,

so its instance methods could be called from a static context. no?

then how come if sometimes fails?

3
  • definitely. You can call static or non static methods of AppWidgetService, but the methods 'setRefreshingState()' and 'refreshHandler()' are static. So either you remove static from your method header or call these methods using instances of these classes. Commented Aug 22, 2013 at 9:28
  • I dont get it. startRefresh is static so it can call setRefreshingState()' and 'refreshHandler()' which are also static. Why do you suggest So either you remove static from your method header or call these methods using instances of these classes. Commented Aug 22, 2013 at 9:31
  • are you sure the calls to startRefresh are the problem? Those should be fine. However, your mInstance variable might be uninitialized? Commented Aug 22, 2013 at 12:31

2 Answers 2

1

From a static function, you can call only static function or use static variable. The linking is done at run time. So, though your compilation will be fine but at run time it will fail when call is made. Try making your function non static if you want to make that call.

OR

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.

Sign up to request clarification or add additional context in comments.

2 Comments

not yet. according to this, it should never fail on runtime. but it does sometimes
please see my new revised question: stackoverflow.com/questions/18377150/…
0

This problem arises when you call a static method from a non-static block/method. In your code both 'setRefreshingState()' and 'refreshHandler()' are static methods. To call theses methods you have to remove static from your method definition.

1 Comment

please see my new revised question: stackoverflow.com/questions/18377150/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.