Android, check if back Button was pressed - java

i have two views and activities.
On the first there is a spinner. On the second, you can create new entries (Stored in database for the spinner in activity 1).
If the user is finished and pressed the back button, i have to refresh the spinner on activity 1 (because of the new entries).
Ist there a possibility to check, if the app returns to activity 1, because the back button in activity 2 was pressed?
I know, i can do it with the onResume Method, but this method is called EVERYTIME i return to activity one and not ONLY because of the back button.
I want to refresh the spinner only when the back button was pressed.
Any solution? Can i Check if the back button was pressed in the onResume method?

You can override onBackPressed() in the Second Activity. This will get called when the user presses the back button.
You can pass the information as a boolean hasBackPressed = true in the setResult()
Starting Activity 2 from Activity 1:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
Passing info back from Activity 2:
#Override
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("hasBackPressed",true);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
Receiving data in Activity 1:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
boolean hasBackPressed = data.getBooleanExtra("hasBackPressed");
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}

You can start Activity 2 for result, using startActivityForResult(). On Activity 2 you can set the result to RESULT_OK when new items have been added. Then, in the onActivityResult() method of Activity 1 you can check the returned result and update your data, if needed.

Override the onBackPressed() method and take the action inside this function.
#Override
public void onBackPressed() {
// your stuff here
super.onBackPressed();
}

Use startActivityForResult() to start the second activity, and return some value in the onBackPressed() of the second activity. Catch that in onActivityResult(), and refresh the spinner there.
Look into this.

Related

How to retain value in second activity after re-clicking the button from MainActivity to launch the second activity?

I have 2 activities. First is MainActivity and second is SecondActivity.
MainActivity has a textView and buttoncalled "Launch". Using intent and startActivityForResult I am passing a list to SecondActivity.
SecondActivity has a spinner and 2 buttons;a select button and a cancel button.
On selection of an item from the spinner, when user clicks on Select button, the option chosen in the spinner is populated in the textView of MainActivity.
Now when the user again clicks on "Launch", SecondActivity launches however, the spinner doesn't hold the value the user had chosen last time, instead it shows the first value of the spinner.
Is their anyway, how I can retain the value selected in the SecondActivity chosen by the user in it's previous use.
When you close the SecondActivity, you should return the select item of spinner to MainActivity. If it is MainActiviy can get that value in this function :
onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
before that, you shold show SecondActivity with
startActivityForResult(intent, SECOND_CODE);
so the code can be like this
private static SECOND_CODE = 1001;
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, SECOND_CODE);
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SECOND_CODE && resultCode ==
Activity.RESULT_OK && data != null) {
// you can get selected spinner item here
}
}
After that, when you want to show SecondActivity again
Intent intent = new Intent(MainActivity.thisSecondActivity.class);
intent.putExtra("selected_spinner", /*the spinner item you got from above function*/)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, SECOND_CODE);
and in SecondActivity, you can get the selected spinner item from getIntent()
String selected_spinner = getIntent().getStringExtra("selected_spinner");
Then you can find this string in Spinner and select it.
You can persist information using SharedPreferences, just store the last selection from the user and then retrieve it to set on SecondActivity.
Context context = getActivity();
SharedPreferences prefs = context.getSharedPreferences(
getString("myPreferences"), Context.MODE_PRIVATE);
//Store a value
SharedPreferences.Editor editor = prefs.edit();
editor.putString("selection","foo");
//Get the value
String selection = prefs.getString("selection", "defaultOption");
Here is the official documentation: https://developer.android.com/training/data-storage/shared-preferences

How can I change the background color of a Main Activity by using spinner while clicking a button in the Second Activity?

I want to change the background color of Main activity by using spinner in second Activity. I have already created one button and it goes to second activity and in this second activity I have created spinner which consist of which color should be in the main activity. After choosing the color, the button I created will change the background color and will be back to first activity.
From what I understand, you need the ActivityForResult behavior.
You use startActivityForResult to fire the Intent from your first activity to your second, along with a request code.
You use an Intent and setResult to send data from your second activity back to your first.
You override onActivityResult in your fist activity to get and use your data.
Sample code:
public class FirstActivity extends Activity {
private static final int PICK_COLOR_REQUEST = 1001;
...
private void pickColor() {
Intent pickColorIntent = new Intent(this, SecondActivity.class);
startActivityForResult(pickColorIntent, PICK_COLOR_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_COLOR_REQUEST && resultCode == Activity.RESULT_OK) {
int color = data.getIntExtra("color");
/* use the color */
}
}
}
public class SecondActivity extends Activity {
...
private void onColorPicked(int color) {
Intent dataIntent = new Intent();
dataIntent.putExtra("color", color);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
}

Selecting a Sound in an activity to be played in another activity

I have this idea that I couldn't code so I'm here Asking for help
I have two activities the first one :
Xml file : Button
Java File : a click listener for the Button to play a sound effect with the SoundPool class from res/raw
--all simple--
what want to do is to create a second activity where the user can choose an other sound effects like Sound1 or Sound2 ...etc from a radio button group, to be played instead.
this was my idea, so please help me coding this I'm stuck since 2 weeks and I have 0 clue whats the next step.
SOS =)
You could define a global variable for the sound effect to play:
int activeSoundEffectRawId = R.raw.defaultSound;
And play it with your SoundPool's load method.
To select the sound to play, you could add another button to your xml file that starts Activity2:
Button btnSelectSound = (Button) findViewById (R.id.button2);
btnSelectSound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(Activity1.this, Activity2.class), 1000);
}
});
It's important that you start the activity for result here with the request code 1000 (this number can be changed for sure).
In your Activity 2 you need the logic to select your sound and for example a "OK" button to save the selection. That ok button will hand over the selected sound to Activity1:
Button btnOk = (Button) findViewById (R.id.ok);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
returnIntent.putExtra("soundRawId", selectedSoundRawId /* <- replace this with the selected sound, like R.raw.yourSound */);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
After that, you can set the selected sound in Activity1:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
selectedSoundRawId = data.getIntExtra("soundRawId");
}
}

Have to press the back button twice to get to previous activity?

I am simply trying to click back and navigate to my previous activity. My flow is this: I go to news_feed activity -> Comments activity -> User Profile activity -> click back (Go to Comments activity) -> click back (This does nothing for some reason) -> Click back (Go back to news_feed activity). I'm not sure why I have to click back twice when I try to go from Comments activity back to news_feed activity. If I go from news_feed activity -> Comments -> press back (Go to news_feed activity) this works perfectly. Here is my code:
news_feed.java:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
Comments.java:
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
UserProfile.java:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(UserProfile.this, Comments.class);
Bundle bundle = new Bundle();
bundle.putString("postId", postId);
bundle.putString("posterUserId", posterUserId);
bundle.putString("posterName", posterName);
bundle.putString("postStatus", postStatus);
bundle.putString("postTimeStamp", postTimeStamp);
bundle.putString("postTitle", postTitle);
intent.putExtras(bundle);
startActivity(intent);
finish();
}
I don't think navigating to these activities would change anything, but I can include the intents that I used to navigate to these activities also if necessary. Otherwise I just included the onBackPressed code that I had for these activities. Any ideas why this might cause a problem? Any help would be appreciated. Thanks.
In your UserProfile class, in onBackPressed() method, you are starting the Comments class again. Why do you have to do this?
What is happening is, you are starting a new Comments activity onBackPressed() of the USerProfile class, so there are two instances of Comments Activity. So you feel you are pressing back btn twice.
If you have to pass data back to Comments from UserProfile class, then make use of setResult() method.
This will be of help
How to pass data from 2nd activity to 1st activity when pressed back? - android
Sending data back to the Main Activity in android
I you want to send back the result to previous activity the start activity by using
startActivityForResult()
insead of
startActivity()
and don't override
onBackPressed()
You can try something like this:
private boolean clicked;
#Override
public void onBackPressed() {
if (!clicked) { // if it was not clicked before, change the value of clicked to true and do nothing directly return, if clicked again, then it will be finish the activity.
clicked=true;
return;
}
super.onBackPressed();
}
And if you are going to use the time, then you can do like this:
private long lastClicked;
#Override
public void onBackPressed() {
if (System.currentTimeMillis() - lastClicked < 1000) { // within one second
super.onBackPressed();
}
lastClicked = System.currentTimeMillis();
}
You don't need to override onBackPressed() if all you're going to do is call startActivity() and finish() in the current activity. The Android backstack will handle both of those for you. Moreover, in your UserProfile.java you are passing data to previous activity. For this, you should use startActvityForResult() in the Comments activity (i.e the previous activity) instead of startActivity().
To learn more about startActvityForResult() visit: https://developer.android.com/training/basics/intents/result.html
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
this.lastBackPressTime = System.currentTimeMillis();
} else {
//super.onBackPressed(); for exit
//INTENT HERE TO YOUR SECOND ACTIVITY like below
Intent intent=new Intent(A.this,B.class);
startActivirty(intent);
}
}
Create a global variable
private long lastBackPressTime = 0;
Hope this will help you,Let me know..

Android: How to go back previous application on back button click [duplicate]

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

Categories

Resources