I have made a action-bar back button in my app with:
Settings.java:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and
AndroidManifest.xml:
<activity android:name=".Settings">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="at.mrminemeet.reviewcheck.MainActivity" />
</activity>
but I experienced that the software-key calls the "onPause" and so but the action-bar one won't do that.
I checked some other posts and so which tell me to try
#Override
public void onBackPressed(){
// stuff
super.onBackPressed();
}
but it didn't do anything. It completly ignores that I added the code.
Did I do anything wrong?
Other posts:
Post 1
Post 2
You need to override onOptionsItemSelected() and use the ID android.R.id.home to override the up botton action. What I would do is call the onBackPressed() function when the home button is pressed. A sample code will look like this
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
getActivity().onBackPressed()
return true;
}
return super.onOptionsItemSelected(item);
}
For further details, you can see the Android documentation on providing up Navigation
Note that the answer below was written before the original question was edited. I am leaving it here and have answered the question above.
Original Answer:
If you are specifically talking about
#Override
public void onBackPressed(){
super.onBackPressed();
// stuff
}
then the problem lies that you call super.onBackPressed() before your code. This call will go back to the previous activity or exit the app depending on which activity it is called on. Instead change it to-
#Override
public void onBackPressed(){
//your code to do stuff here
super.onBackPressed();
}
and it will first execute your code and then go back.
I want to do something simple on android app.
How is it possible to go back to a previous activity.
What code do I need to go back to previous activity
Android activities are stored in the activity stack. Going back to a previous activity could mean two things.
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
Keep track of the activity stack. Whenever you start a new activity with an intent you can specify an intent flag like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_PREVIOUS_IS_TOP. You can use this to shuffle between the activities in your application. Haven't used them much though. Have a look at the flags here: http://developer.android.com/reference/android/content/Intent.html
As mentioned in the comments, if the activity is opened with startActivity() then one can close it with finish().
If you wish to use the Up button you can catch that in onOptionsSelected(MenuItem item) method with checking the item ID against android.R.id.home unlike R.id.home as mentioned in the comments.
Try Activity#finish(). This is more or less what the back button does by default.
Just write on click finish(). It will take you to the previous Activity.
Just this
super.onBackPressed();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
This will get you to a previous activity keeping its stack and clearing all activities after it from the stack.
For example, if stack was A->B->C->D and you start B with this flag, stack will be A->B
Just call these method to finish current activity or to go back by onBackPressed
finish();
OR
onBackPressed();
Are you wanting to take control of the back button behavior? You can override the back button (to go to a specific activity) via one of two methods.
For Android 1.6 and below:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}
return super.onKeyDown(keyCode, event);
}
Or if you are only supporting Android 2.0 or greater:
#Override
public void onBackPressed() {
// do something on back.
return;
}
For more details: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
Try this is act as you have to press the back button
finish();
super.onBackPressed();
Add this in your onCLick() method, it will go back to your previous activity
finish();
or You can use this. It worked perfectly for me
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if ( id == android.R.id.home ) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
if you want to go to just want to go to previous activity use
finish();
OR
onBackPressed();
if you want to go to second activity or below that use following:
intent = new Intent(MyFourthActivity.this , MySecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Bundle is optional
Bundle bundle = new Bundle();
bundle.putString("MyValue1", val1);
intent.putExtras(bundle);
//end Bundle
startActivity(intent);
If you have setup correctly the AndroidManifest.xml file with activity parent, you can use :
NavUtils.navigateUpFromSameTask(this);
Where this is your child activity.
Got the same problem and
finish(); OR super.onBackPressed();
worked fine for me, both worked same, but no luck with return
You can explicitly call onBackPressed is the easiest way
Refer Go back to previous activity for details
Start the second activity using intent (either use startActivity or startActivityForResult according to your requirements). Now when user press back button, the current activity on top will be closed and the previous will be shown.
Now Lets say you have two activities, one for selecting some settings for the user, like language, country etc, and after selecting it, the user clicks on Next button to go to the login form (for example) . Now if the login is unsuccessful, then the user will be on the login activity, what if login is successful ?
If login is successful, then you have to start another activity. It means a third activity will be started, and still there are two activities running. In this case, it will be good to use startActivityForResult. When login is successful, send OK data back to first activity and close login activity. Now when the data is received, then start the third activity and close the first activity by using finish.
You can try this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
All new activities/intents by default have back/previous behavior, unless you have coded a finish() on the calling activity.
#Override
public void onBackPressed() {
super.onBackPressed();
}
and if you want on button click go back then simply put
bbsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
I suggest the NavUtils.navigateUpFromSameTask(), it's easy and very simple, you can learn it from the google developer.Wish I could help you!
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if ( id == android.R.id.home ) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Try this it works both on toolbar back button as hardware back button.
There are few cases to go back to your previous activity:
Case 1: if you want take result back to your previous activity then
ActivityA.java
Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
startActivityForResult(intent,2);
FBHelperActivity.java
Intent returnIntent = new Intent();
setResult(RESULT_OK, returnIntent);
finish();
Case 2: ActivityA --> FBHelperActivity---->ActivityA
ActivityA.java
Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
startActivity(intent);
FBHelperActivity.java
after getting of result call finish();
By this way your second activity will finish and because
you did not call finish() in your first activity then
automatic first activity is in back ground, will visible.
Besides all the mentioned answers, their is still an alternative way of doing this, lets say you have two classes , class A and class B.
Class A you have made some activities like checkbox select, printed out some data and intent to class B.
Class B, you would like to pass multiple values to class A and maintain the previous state of class A, you can use, try this alternative method or download source code to demonstrate this
http://whats-online.info/science-and-tutorials/125/Android-maintain-the-previous-state-of-activity-on-intent/
or
http://developer.android.com/reference/android/content/Intent.html
Just try this in,
first activity
Intent mainIntent = new Intent(Activity1.this, Activity2.class);
this.startActivity(mainIntent);
In your second activity
#Override
public void onBackPressed() {
this.finish();
}
First, thing you need to keep in mind that, if you want to go back to a previous activity. Then don't call finish() method when goes to another activity using Intent.
After that you have two way to back from current activity to previous activity:
Simply call:
finish()
OR
super.onBackPressed();
To go back from one activity to another by clicking back button use the code given below use current activity name and then the target activity.
#Override
public void onBackPressed() {
// do something on back.
startActivity(new Intent(secondActivity.this, MainActivity.class));
return;
}
I'm running an emulator for google glass as seen here, works pretty flawlessly by showing settings, main display and even my activity (which I pretend to be an interactive static card).
http://mobilevangelist.com/2014/01/02/gdk-and-the-android-emulator/
I've seen that the motion gestures are captured using onKeyUp or onKeyDown events but neither are working and I don't understand why.
Here is my code.
public class LiveCardMenuActivity extends Activity {
private TextView textView;
#Override //isn't catching a thing, even with onKeyDown (mouse taps or slides in the emulator)
public boolean onKeyUp(int keycode, KeyEvent event){
Log.d("tag","keyUp");
if(keycode == KeyEvent.KEYCODE_DPAD_CENTER){
Log.d("tag","keypadcenter");
textView.setText("tap");
}else if(keycode == KeyEvent.KEYCODE_BACK){
Log.d("tag","swipedown");
textView.setText("down");
}
return true;
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
setContentView(R.layout.live_card);
//does successfully, I can see the layout in the emulator
//and I can swipe it to the left (returning to the main display successfully)
textView = (TextView) findViewById(R.id.textView);
Log.d("tag","attached to window");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.live_card, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_stop:
// Stop the service which will unpublish the live card.
stopService(new Intent(this, LiveCardService.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onOptionsMenuClosed(Menu menu) {
super.onOptionsMenuClosed(menu);
// Nothing else to do, finish the Activity.
finish();
}
}
Can someone help me on this one? Tyvm!
Try calling setFocusable(true) on your content view.
Though I don't know much about how this emulator works, this is how you might get this working for standard Android.
You're using onKeyUp() when you need to be using onKeyDown(). Here's an example I'm using in my Glass project (but I have a physical Google Glass, not using an emulator):
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch( keyCode ) {
case KeyEvent.KEYCODE_DPAD_CENTER:
Log.e("GESTURE_EVENT", "PostVideoActivity.onKeyDown() TAP/KEYCODE_DPAD_CENTER");
// DO SOMETHING
return true;
case KeyEvent.KEYCODE_BACK:
Log.e("GESTURE_EVENT", "PostVideoActivity.onKeyDown() SWIPE/KEYCODE_BACK");
// DO SOMETHING
return true;
default:
Log.wtf("GESTURE_EVENT", "PostVideoActivity.onKeyDown() DEFAULT -- SHOULDNT BE HERE!");
return false;
}
}
edit Maybe this is an issue with the emulator? I doubt it though but you can test this theory by creating some dummy Android project for a phone/phone emulator that is known to work. If this snippet doesn't even work for the other Android emulation then maybe its something else?
Below is the code for my submenu buttons and I'm trying to make it delete the note and return to the main list view. The delete option is called "Red" for now.
I copied my delete code from my main activity thinking it would work, but it does not. I'm very new to android coding, so help would be appreciated.
This is how I delete in my Main Activity.java
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
currentNoteId = (int)info.id;
menu.add(0, MENU_DELETE_ID, 0, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == MENU_DELETE_ID) {
Noteitem note = notesList.get(currentNoteId);
datasource.remove(note);
refreshDisplay();
}
return super.onContextItemSelected(item);
}
Here is my code for my NoteEditorActivity.java
Again I'm trying to delete, but I can't seem to figure out how to delete the note from the submenu.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_exit:
EditText et = (EditText)findViewById(R.id.noteText);
if (et.length() > 0) {
saveAndFinish();
}
else
{
finish();
}
case R.id.menu_red:
currentNoteId = (int) MENU_DELETE_ID;
datasource.remove(note);
return true;
default:
return super.onOptionsItemSelected(item);
}
Put break statements in your switch case
switch (item.getItemId())
{
case R.id.action_exit:
EditText et = (EditText)findViewById(R.id.noteText);
if (et.length() > 0){
saveAndFinish();
}else{
finish();
}
//you are missing this!!!
break;
case R.id.menu_red:
datasource.remove(note);
finish();
break;
default:
return super.onOptionsItemSelected(item);
break;
}
Try reading this here also: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
its just weird..you aren't calling notesList.add() method anywhere in your code, so I just think it's empty at all..
you are certainly missing the break statement there, but I guess it is not the issue why your note is not deleted after clicking in the menu item. You are saving your note in the "previous" (in terms of backstack) activity? if so, you might try to just alter the return code for the setActivityResult() call (or add some extras to the intent) and then check for it in your onActivityResult() callback..
because right now everytime you close the activity via back key, the notes is saved (the saveAndFinish() method gets called);
please describe better where you actually do save notes (to DB or so) and where you wanna delete them..I could then provide you with some code snippet probably.
I'm 100% sure this is going to be one of those newbie questions, but here it goes...
Is there a way I can write a method in one activity and be able to access it from the others?
Example:
I have six activites in my app, each with it's own menu.xml because the options available for each need to be different, and I have these menus & menuitems set up as shown:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.calculator_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handle item selection
switch (item.getItemId()) {
case R.id.menuItem_calculator_Help:
helpDialogGo();
return true;
case R.id.menuItem_calculator_Settings:
//settingsActivityGo();
return true;
case R.id.menuItem_calculator_Share:
shareGo();
return true;
case android.R.id.home:
// app icon in Action Bar clicked; go home
Intent uptohome = new Intent(this, Main.class);
uptohome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(uptohome);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The an example of one of these methods is:
private void helpDialogGo() {
Toast.makeText(this, "help", Toast.LENGTH_LONG).show();
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Sorry, no help has been written since this application is still in development. This is a prerelease version.")
.setCancelable(false)
.setPositiveButton("Cool", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'Yes' Button
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Pixel Help");
// Icon for AlertDialog
alert.setIcon(R.drawable.question);
alert.show();
}
So is there a way to have this custom method shared among all the activities and run it when the button is pressed in each of them, as to avoid having large amounts of code replicated across my app?
And if so, are there any potholes that I may hit? (Some of the menu items are going to bring up dialogs, others will take the user to a new activity)
Do you have similar menuitems in every activity? i.e. same number of items but different behaviour? If yes...
How about creating a BaseActivity which overrides onCreateOptionsMenu and onOptionsItemSelected() methods.. (As you have given in the above example). All your activities should inherit from this BaseActivity and then override the menu handling methods. eg. helpDialogGo() will go to the new class.
so the BaseActivity will have onCreateOptionsMenu and onOptionsItemSelected() methods. Plus all the menuItem actions (i.e. helpDialogGo() etc) as empty methods. The inherited classes will overide menuItem Actions.
If the menuitems are not similar in each activity, you are better off creating menu for each activity.
EDIT:
Not sure what you expect more. I thought I made it clear. Let me try again.
Class BaseActivity extends Activity.
BaseActivity extends Activity {
// Copy your onCreateOptionsMenu() and onOptionsItemSelected() methods here
protected void helpDialogGo() { }
// ... other methods
}
Class MyActivity1 extends BaseActivity.
MyActivity1 extends BaseActivity {
// Copy your helpDialogGo() code in full here and then make
// any specific changes to menu behaviour based on activity.
}
Class MyActivity2 extends BaseActivity
MyActivity2 extends BaseActivity {
// Copy your helpDialogGo() code in full here and then make
// any specific changes to menu behaviour based on activity.
}
One way, of course, is to created some custom classes that encapsulate your desired functionality - and use those within your activities. It's a better abstraction than placing the implementation directly in the Activity(s) itself (all things being equal, and based on what you described so far).
Any time you find yourself duplicating an implmentation that's a flag reminding you this is a good place to roll that code into its own class - usually.