I tried most ways to reload a webview in every 10 seconds, such as using threads, timers, ScheduledExecutiveService... but every time I try, my app crashes. Here is my code...
public class MainActivity extends AppCompatActivity {
String user;
String password;
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = getIntent();
user = i.getStringExtra("username");
password = i.getStringExtra("password");
webView = (WebView) findViewById(R.id.webView);
final WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(final WebView view, String url) {
view.loadUrl("javascript: (function() {document.getElementById('ft_un').value= '" + user + "';}) ();");
view.loadUrl("javascript: (function() {document.getElementById('ft_pd').value= '" + password + "';}) ();");
view.loadUrl("javascript:(function(){ document.querySelectorAll(\"input[type='submit']\")[0].click();})();");
super.onPageFinished(view, url);
}
});
//After this is i am getting error this is my timer and below that is the code to reload a webview
new Timer().schedule(new TimerTask(){
@Override
public void run() {
// TODO Auto-generated method stub
refresh();
}}, 10000, 10000);
}
public void refresh() {
// TODO Auto-generated method stub
webView.loadUrl("javascript:window.location.reload(true)");
}
}
And the error i got is here:
FATAL EXCEPTION: Timer-0
Process: com.anshuman.cgcautologin, PID: 5318
java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'Timer-0'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {256ea4a6} called on null, FYI main Looper is Looper (main, tid 1) {256ea4a6})
at android.webkit.WebView.checkThread(WebView.java:2204)
at android.webkit.WebView.loadUrl(WebView.java:851)
at com.anshuman.cgcautologin.MainActivity.refresh(MainActivity.java:72)
at com.anshuman.cgcautologin.MainActivity$2.run(MainActivity.java:64)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Caused by: java.lang.Throwable: A WebView method was called on thread 'Timer-0'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {256ea4a6} called on null, FYI main Looper is Looper (main, tid 1) {256ea4a6})
at android.webkit.WebView.checkThread(WebView.java:2194)
at android.webkit.WebView.loadUrl(WebView.java:851)
at com.anshuman.cgcautologin.MainActivity.refresh(MainActivity.java:72)
at com.anshuman.cgcautologin.MainActivity$2.run(MainActivity.java:64)
at java.util.Timer$TimerImpl.run(Timer.java:284)