-5

I want to create an app for WebView in android, how i can stop the WebView with "onPause()" i have tried to use this code:

    @Override
public void onPause(){
    super.onPause();
    WebView.pauseTimers();
}

But it don't work, it says:

Error: non-static method pauseTimers() cannot be referenced from a static context

This is the all code of WebView

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    WebView myWebView = (WebView) findViewById(R.id.webview);

    myWebView.setWebViewClient(new WebViewClient());

    myWebView.loadUrl("MyURL");

    WebSettings webSettings = myWebView.getSettings();

    webSettings.setJavaScriptEnabled(true);

}
Pietroos
  • 27
  • 9
  • 1
    Sorry, could you elaborate on what you're trying to say? At the moment your question makes little sense. Include some relevant code if that helps. `public` and `private` only affect visibility of classes within your own app. – Michael Dodd Mar 25 '18 at 18:02
  • Hi, i have re-elaborated the message – Pietroos Mar 25 '18 at 20:04

1 Answers1

2

You're trying to access a non-static method in a static way. Firstly a quick explaination of what a static method does. Consider this class:

public class ClassA {
    public void methodOne() {}
    public static void methodTwo() {}
}

methodOne is an Instance method. This can only be called from an instance of ClassA declared with the new keyword, like so:

ClassA myClassA = new ClassA();
myClassA.methodOne();

methodTwo is static, therefore it belongs to the class itself, and not any particular instance of that class. The downside of this is that static methods cannot access member variables unless they too are declared static:

ClassA.methodTwo();

In your case, you need to call pauseTimers() on the instance of the WebView object you've declared in your Activity or layout. So from your code posted above:

private WebView myWebView; // Move this declaration out from onCreate()

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    myWebView = (WebView) findViewById(R.id.webview);

    // rest of the method...
}

@Override
public void onPause() {
    super.onPause();
    myWebView.pauseTimers();
}

Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
  • I've chosen to answer rather than raise a duplicate as I've already used up my flag for this question, before the extra information was provided. However, the relevant dupe would be this: https://stackoverflow.com/questions/4969171/cannot-make-a-static-reference-to-the-non-static-method – Michael Dodd Mar 25 '18 at 20:16