First off, I don't really know anything about Java at all.. I do front end dev and that's really it, I have tried looking through documentation and tutorials but am having issues.. I have a website and I am trying to get it to work on Android. I have pretty much everything working except pressing back on an Android device exits the app (Which is expected from what i've read)
@Override
public void onBackPressed() {
if (WebView.canGoBack()) {
WebView.goBack();
} else {
super.onBackPressed();
}
}
Is what I tried adding to my code however I get the errors:
Error:(45, 24) error: non-static method canGoBack() cannot be referenced from a static context
Error:(46, 24) error: non-static method goBack() cannot be referenced from a static context
Error:(48, 22) error: cannot find symbol method onBackPressed()
Error:(43, 9) error: method does not override or implement a method from a supertype
Many thanks in advance!
P.S - Here is the full code.
package com.appname.appname;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.myWebView);
myWebView.loadUrl("http://www.website.com");
myWebView.setWebViewClient(new MyWebViewClient());
//Settings
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
private class MyWebViewClient extends WebViewClient {
//Open links internally
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.website.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
//Back Button Fix
@Override
public void onBackPressed() {
if (WebView.canGoBack()) {
WebView.goBack();
} else {
super.onBackPressed();
}
}
}
}
Thank you.
EDIT: I had also tried this code I found in another Stack post.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (WebView.canGoBack()) {
WebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
I was told in a tutorial to press ctrl+o (In Android Studio) and select an Override for onKeyDown, but that isn't in my list. I then found that the onKeyDown was for pre 2.0 Phones? So I tried looking for onBackPressed but I couldn't find that either. I know this is going to be something really easy..