Use capacitive Back button to goBack(); in fragment activity in eclipse - java

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;
}

Related

Android MediaRecorder Fragment how to keep the same instance

I have a MediaRecorder class, that extends Fragment. Inside that class I have created methods to set up the MediaRecorder and also methods to start and stop recording.
I have tried creating onTouch withing the Fragment and using start/stop inside the fragment on button presses and it worked. But when I removed onTouch and tried to use the start/stop methods from another class I got NullPointerException. To be more precise, it gave no error when pressing start but gave an error when I pressed stop!
After debugging startRecordingVideo all 3 -> (mCameraDevice, mTextureView, mPreviewSize) are null so it does not even start recording and during stopRecordingVideo the mMediaRecorder is also null.
Here is the part where I try to use the MediaRecorderFragment inside another class:
private Camera2VideoFragment camera2VideoFragment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.song_player);
//Camera2Video
camera2VideoFragment = new Camera2VideoFragment();
//Start Camera Preview
getFragmentManager().beginTransaction()
.replace(R.id.container, Camera2VideoFragment.newInstance())
.commit();
playRecordButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionevent) {
final int action = motionevent.getAction();
if (action == MotionEvent.ACTION_DOWN) {
//Start recording video
startRecordingVideo();
} else if (action == MotionEvent.ACTION_UP) {
//Stop Recording Video
stopRecordingVideo();
}
return false;
}
});
}
private void startRecordingVideo(){
camera2VideoFragment.startVideoRecording();
}
private void stopRecordingVideo(){
camera2VideoFragment.stopVideoRecording();
}
The MediaRecorderFragment can be found here. (This class is too long to post here).
My question is, why do I get the NullPointerException and how can I make that fragment work from another class.

getting force close error on back key

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;
}
}

Handling the Back Button

I am working on the following code:
private class HandleBackButton implements OnKeyListener
{
#Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
if(arg1==KeyEvent.KEYCODE_BACK)
{
showResults(0);
}
return true;
}
}
I am somewhat new to android and my purpose is to operate the above code when the back button is clicked. User can click the back button any time. But, how can I set this listener to the Activity? I can't find something like this.setOnKeyListener().
I am using Android 2.3.3.
For the Activity you should override onBackPressed which is invoked when you press the back button. OnKeyListener dispatches key events to the view. You find setOnKeyListener defined in the View class
Interface definition for a callback to be invoked when a hardware key
event is dispatched to this view. The callback will be invoked before
the key event is given to the view. This is only useful for hardware
keyboards; a software input method has no obligation to trigger this
listener.
Just override the onKeyDown() method of Activity.
You don't have to set a listener then.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
showResults(0);
return true;
}
return super.onKeyDown(keyCode, event);
}
Optionally you can also override onBackPressed() if your api level is >= 5.
You can use onBackPressed():
#Override
public void onBackPressed() {
showResults(0);
}

Android : startActivityForResult() with BACK button functionality

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().

The method onBackPressed() of type FirstGroup must override a superclass method

I'm trying to override the onBackPressed() method of the ActivityGroup class:
public class MyClass extends ActivityGroup {
#Override
public void onBackPressed() {
// do something
return;
}
but I'm getting the error The method onBackPressed() of type MyClass must override a superclass method.
I'm relatively new to Java, I've seen here that people do it and it works for them
Why I'm getting this error?
I'm writing an app for android 1.5, could the problem be here?
Edit
You need to override the back button like this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "back button pressed");
}
return super.onKeyDown(keyCode, event);
}
Yes u r correct onBackPressed() method has been introduced only in API Level 5 which means you can use it only from 2.0 SDK

Categories