I'm having a problem when I press the back key to leave game at this web site. I get a forced error message on back key. I used the destroy code I learned from my first question. Didn't change anything. Any ideas?
public class MainActivity extends Activity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webView1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.limejs.com/static/roundball/index.html");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
finish();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up
// to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
#Override
public void onDestroy() {
super.onDestroy();
myWebView.destroy();
}
}
Here is the Logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.roundball.MainActivity.onKeyDown(MainActivity.java:33)
at android.view.KeyEvent.dispatch(KeyEvent.java:1256)
at android.app.Activity.dispatchKeyEvent(Activity.java:2078)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent
(PhoneWindow.java:1771)
at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2563)
at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2538)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1870)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)`enter code here`
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at dalvik.system.NativeStart.main(Native Method)
I have used this code before to load web sites, it is just particular to this game?
i would remove the return true; right after the finish();
It would help if you had some adb logs to show the exact error you are getting.
You can also check to see if myWebView is not null. I am thinking that might be null as well.
Your log says:
java.lang.NullPointerException at
com.example.roundball.MainActivity.onKeyDown(MainActivity.java:33)
Which means there is a null reference in the code inside the onKeyDown method at the moment of execution. You only use 2 references there, but since its unlikely that you receive a null KeyEvent (it comes from the Android Runtime and documentation says implicitly that you always receive a valid reference when onKeyDown is called), it has to be the reference to your webview. So check if myWebView != null before calling myWebView methods, like this.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if(myWebView != null) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
finish();
return true;
}
} else {
android.util.Log.w("MyActivity", "myWebView is null!!");
}
// If it wasn't the Back key or there's no web page history, bubble up
// to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
From that code I can't tell what is causing you to have a null reference to the webview, but It might tell you where to look next for the problem if you expect your webview reference to be not null.
change your code to the code given below.. basically.. i updated your call to finish() to MainActivity.this.finish() , where MainActivity is your activity! So, you will have to change MainActivity to whatever name you gave.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
MainActivity.this.finish();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up
// to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
//replace for this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
if (keyCode != KeyEvent.KEYCODE_BACK){
return MainActivity.onKeyDown(keyCode, event);
}else{
myWebView.destroy();
MainActivity.finish();
return false;
}
}
Related
I'm having trouble overriding the Back Button press on Android.
The thing is, everything works perfectly except for the very first time.
When I load the app and press the back button for the first time, it pauses the app, which is NOT what I want. Other than that, it works as expected.
My code:
private void setupDeviceButtons(){ // this is ran at the very beginning (onViewCreated())
// setting up a listener to close the menus when the back button is pressed
View view = getView();
Log.e(TAG, "This happens when I load the app" );
if (view != null) {
Log.e(TAG, "This also happens when I load the app");
view.setOnKeyListener((v, keyCode, event) -> {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Log.e(TAG, "But this doesn't happen when I press the back button for the first time.");
// we filter all actions that are not key down
if (event.getAction() != KeyEvent.ACTION_DOWN)
return true;
...
}
return false;
});
} else {
Log.e(TAG, "ERROR on setupDeviceButtons(): Unable to set back button behaviour. View is null.");
}
}
Any thoughts?
Thank you in advance
Use the below code working perfectly in fragments.
//on fragment back pressed
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction()== KeyEvent.ACTION_DOWN) {
// do your code on back pressed
return true;
}
return false;
}
});
I have an app that plays some music file while the application is open but when i press the power button the sound keeps playing for some reason. Is there a way to override the power button so it will also stop the media player when pushed ?
MediaPlayer mp;
protected void onCreate(Bundle savedInstanceState) {
...
...
mp = MediaPlayer.create(this, mAudio[0]);
mp.start();
...
...
}
I would like to call mp.stop() when the power button is pressed.
Override onKeyDown and check if it's KEYCODE_POWER.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
// Stop the media player here
return true;
}
return super.onKeyDown(keyCode, event);
}
Add this method:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
// stop the media from playing
return true;
}
return super.onKeyDown(keyCode, event);
}
This method is being activated when a key is being pressed. It checks what key is pressed and reacts for it.
First of all you need to understand, when you want to pause or stop the sound. If you want to do it, when you exit/hide an application, then overriding onKeyDown won't help. I think better approach in this case will be:
protected void onCreate(Bundle onSaveInstanceState) {
super.onCreate(onSaveInstanceState);
mp = MediaPlayer.create(this, mAudio[0]);
}
protected void onStart() {
super.onStart();
mp.start();
}
protected void onStop() {
super.onStop();
mp.stop();
}
But if you want to stop your sound only when Power button is pressed, then yes, you need to override onKeyDown
I'm trying to program for android and I'm having a little problem. I made an app, but I can not make the back of the phone button, return to the previous page without completely closing the app. I'm working with WebView.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
// CODIGO DO WEB VIEW
final WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl("http://www.idestudos.com.br");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
myWebView.setWebViewClient(new MyBrowser());
myWebView.setWebViewClient(new WebViewClient() { //CODE WEBVIEW}
Easy implemented by calling canGoBack.
if(webView.canGoBack()) {
webView.goBack();
}
And calling it from inside onBackPressed method in activity like this:
#Override public void onBackPressed() {
if(webView != null && webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
Here's a solution:
When your WebView overrides URL loading, it automatically accumulates a history of visited web pages. You can navigate backward and forward through the history with goBack() and goForward().
For example, here's how your Activity can use the device Back button to navigate backward:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
Check out the Building Web Apps in WebView Android Developers Guide for more info
Hope it helps you!
i have build a new app and in that app i have 3 fragments with webview in it. basically i want to implement goBack(); on capacitive back button. i did tried
#Override
public void onBackPressed() {
webView.goBack();
return;
}
and also
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
webView.goBack();
return false;
}
return super.onKeyDown(keyCode, event);
}
but i end up with errors. so can anyone help me doing this. Thank you
and it is a
public class AdminM extends FragmentActivity implements ActionBar.TabListener
You get "The method onBackPressed() of type AdminM.Fragment2 must override or implement a supertype method" because you added Override annotation, but there is no onBackPressed method in Fragment. You can override onBackPressed only in an Activity.
You can look at the Activity and Fragment docs to see what methods you can override and what methods you can not override.
The right way would be to retrieve the Fragment from FragmentManager every time before accessing it. This way you can be sure you're using the right instance. If the Fragment is null, it's not attached.
In Activity
#Override
public void onBackPressed() {
final WebViewFragment fragment = (WebViewFragment) fragmentManager.findFragmentById(fragmentId);
if (fragment == null || !fragment.onBackPressed()) {
super.onBackPressed();
}
}
In Fragment, create a method that returns true if WebView got back and false if not.
Check every time if webView is null, because fragmen has it's own lifecycle mechanism.
public boolean onBackPressed() {
if (webView != null && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
I would like to start a new activity for a result, with startActvityForResult(), but I would like to have the back button working as normal in the new activity.
Currently when I invoke a new Activity for result, nothing happens when I press the back button in the new Activity.
I tried something like this:
#Override
public void onBackPressed() {
setResult(0);
super.onBackPressed();
finish();
}
in the new Activity, but it didn't work. Still nothing happens when the back button is pressed.
Is there a way around this?
EDIT : I could of course load the last Activity in the onBackPressed() (can I?), but it seems like a rather crappy hack.
Alex Ady's answer solves my problem, but I still don't understand why onBackPressed() doesn't work. The working code now is something like this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
setResult(1);
finish();
}
return super.onKeyDown(keyCode, event);
}
I could use an explanation.
You could try
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
}
return super.onKeyDown(keyCode, event);
}
You shouldn't have to override the Back button behavior at all. By default, if the user presses the back button, the result will be Activity.RESULT_CANCELED.
Try getting rid of the line that contains the finish().