I have MainActivity with BottomNav which includes 3 Fragments A, B, and C.
From Fragment A, I can go to Activity A and from, Activity A I can go to Activity B.
Now I want to return to specifically Fragment A from Activity B by pressing a Back button while skipping Activity A.
I've tried Intent.FLAG_ACTIVITY_CLEAR_TASK in Activity A before starting Activity B and also explicitly starting an Intent to MainActivity from Activity B but it's not giving the result I want and of course it doesn't seem like an efficient way to do it. How do I return back to the fragment?
Case 1
You need to finish Activity A after launching intent.
Intent intent = new Intent(ActivityB.this,ActivityA.class);
startActivity(intent);
finish();
case 2
If you want to come back on Activity A at some point then what you need is passing some flag from Activity B to A. And run this code at the beginning of your activity A.
if(extras.getBoolean("NameOfFlag", false))
{
ActivityA.finish();
}
send flag by using this code.
Intent i = new Intent(ActivityB.this, ActivityA.class);
i.putExtra("NameOfFlag", true);
startActivity(i);
finish();
Remember to finish() Activity when you don't need to come back. In this case ActivityB .
Maybe it is not the ideal solution but should work
In Activity B
#Override
public void onBackPressed() {
Intent i = new Intent(ActivityB.this, MainActivity.class);
i.putExtra("cameFromActivityB", true);
startActivity(i);
}
In Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
Bundle extras = getIntent.getExtras();
if(extras.getBoolean("cameFromActivityB", false))
{
loadFragmentA();
}
}
// Inside the onCreate on every Activity://
getSupportActionBar().setTitle("name of the Activity here");
getSupportActionBar().setDisplayHomeAsUpEnable(true);
//then go to the manifest file in //
//before that closing bracket
set the order of your Activities; example
(you have three activities,the Main Activity,Activity2,Activity3)//
<activity android:name=".Activity2"
android:parentActivityName=".MainActivity"></activity>
What you can do is when you start your ActivityB from ActivityA just finish your activityA by finish() method.
Intent intent = new Intent(ActivityB.this,ActivityA.class);
startActivity(intent);
finish();
By doing this you will not be redirected to ActivityA instead, you will be directy redirected to your main activity when you press back button from your activityB.
Related
I'm looking for a solution to press the (non-personalized ads) button of the ActivityPolicies and close the MainActivity and then reopen the MainActivity with the correct ad.
MainActivity(principal)
public void politicas(View view) // button
{
Intent i = new Intent (this, ActivityPolicies.class);
i.putExtra("valor","politicas");
startActivity(i);
}
ActivityPolicies
public void NonPersonalizedAdvertising(View view) //button
{
SharedPreferences myPreferences = PreferenceManager.getDefaultSharedPreferences(MensajePoliticas.this);
SharedPreferences.Editor myEditor =myPreferences.edit();
myEditor.putString("POLITICAS","LEIDO_NOACEPTADO");
myEditor.commit();
//Missing some option to close the main activity
*
*
*
//Reopen the main activity
Intent entrar=new Intent(this,MainActivity.class);
startActivity(entrar);
finish(); // Close the current activity (ActivityPolicies)
}
The goal is to close the MainActivity to reload the correct personalized or non-personalized ad. I already have the code but I am missing this option to reload the MainActivity.
Another question:
Close the main activity to reload the ads, can I have problems with some Admob rule?
Thank you very much
If your MainActivity is in backstack, you can call same activity like this:
Intent entrar = new Intent(this,MainActivity.class);
entrar.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // this will open the same MainActivity instance and also give you a new intent.
startActivity(entrar);
Now in your MainActivity you can override onNewIntent
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// here you will get the new Intent. You can reload only the ads programmatically or just call `this.recreate();`
}
I am opening a fragment1 on Activity A and go fragment1 to Activity B and back again fragment1 when i went again fragment1 to Activity B then click on button (Activity B) then re open Activity B. but i want finish this activity B and open again Activity A if i do without back press ( Activity A -> fragment1 -> Activity B -> onClick button ) then it work fine.
one more thing if i back press 2 or more time then ActivityB also re-open 2 or more time. here I try with onBackPressed():
#Override
public void onBackPressed() {
theatreList.clear();
finish();
super.onBackPressed();
}
and there is onClick of button( Activity B)
Intent intent = new Intent();
intent.putExtra("bundleIds", bundleIds);
setIntent(intent);
finish();
and finish() function:
#Override
public void finish() {
setResult(RESULT_OK, getIntent());
super.finish();
}
Have you try this ?
if ( getFragmentManager().getBackStackEntryCount() == 1) { finish(); } else { super.onBackPressed(); }
I have 3 activities , Activity A and Activity B both can access to Activity C.
But at a time,I am using Intent to return back to previous activity.
Intent i = new Intent(C.this , A.class);
Here i use activity C to return back to Activity A.
but i want to return to activity A or B from C depending upon who called it.
Not using finish(); to return back to activity.
If A calls C then intent i = new Intent (C.this, "dynamically set A");
If B calls C then intent i = new Intent (C.this, "dynamically set B");
Pass a bundle in first call(A to C or B to C) and check where it's came from when clicking back action.
You can simply use finish() method without using the intent. Look at this:
Button button = this.findViewById(R.id.backButton);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
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..
I have three activities: First, Second and Third. I used this method in Second activity:
public void onBackPressed() {
super.onBackPressed();
finish();
}
and this on Third activity:
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent(Third.this, Second.class);
startActivity(i);
finish();
}
The problem is when I press back button after coming from the Third activity, I am going into First activity instead of finish(). I am successfully exiting the application when I click back button right after coming from first activity but not after coming from Third activity.
How to solve this problem?
EDIT: Thanks for the answers guys,the answer of "Ved Prakash" solved the problem for me.But i have a weird problem now.When i press back button the app is successfully exiting but the app which i minimized to Recent Apps button is coming on to the screen and exiting.For example,if i have opened Setting app before opening my app,when i press back button,my app is exiting and immediately Settings app is also opening and exiting itself.What might be the problem?
Your problem is that you don't seem to understand how Activities work. The finish() function ends the current Activity, and then you receive the previous Activity from the backstack.
My recommendation is that you should use a single Activity, and hold Fragments inside it. If you want it so that pressing the Back button ends the application at any screen that is displayed, you could do the following:
Activity XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/initial_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Activity that holds the Fragments:
public class InitialActivity extends FragmentActivity implements ReplaceWith
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initial);
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
{
public void onBackStackChanged()
{
int backCount = getSupportFragmentManager().getBackStackEntryCount();
if (backCount == 0)
{
finish();
}
}
});
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.initial_container, new FirstFragment()).commit();
}
}
#Override
public void replaceWith(Fragment fragment)
{
getSupportFragmentManager().beginTransaction().replace(R.id.initial_container, fragment).commit();
}
}
Example for a Fragment:
public class FirstFragment extends Fragment implements View.OnClickListener
{
private ReplaceWith activity_replaceWith;
private ImageView exampleImage;
public FirstFragment()
{
super();
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
activity_replaceWith = (ReplaceWith) activity;
}
catch (ClassCastException e)
{
Log.e(getClass().getSimpleName(), "Activity of " + getClass().getSimpleName() + "must implement ReplaceWith interface!", e);
throw e;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
exampleImage = (ImageView) rootView.findViewById(R.id.fragment_first_example_image);
exampleImage.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v)
{
if(v == exampleImage)
{
activity_replaceWith.replaceWith(new SecondFragment());
//please note that this should be done only if you are planning
//only on single-screen applications
//with no other layouts based on orientation or size
//otherwise, the Activity needs to be responsible for this, not the Fragment
}
}
}
This way, when you press the Back button, your application would end from any displayed screen.
Ok your code is wrong.
If you will look at activity source, you see that activity.onBackPressed() is calling finish(). So if call super.onBackPressed() you don't need to call finish.
Finish() is not stopping your application, it's stopping current activity.
Your code on third activity very strange. You are trying to stop activity and start another same activity.
What exactly you want to achieve?
If you want to exit application from your third activity, you need to clear your backstack. But I think you have problem with structure of your app.
Ok. then you should finish your first activity when you go to second activity like this(If you are using intent for that):
Intent it=new Intent(FirstActivity.this,SecondActivity.class);
finish();
startactivity(it);
and same for Second Activity:
Intent it=new Intent(SecondActivity.this,ThirdActivity.class);
finish();
startactivity(it);
this done your work...when you are in third activity the above activities are finished..
and when you press backButton you will be exit from application..
Good luck.
You can use -
public static final int FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the
current task, then instead of launching a new instance of that
activity, all of the other activities on top of it will be closed and
this Intent will be delivered to the (now on top) old activity as a
new Intent.
And here is how -
When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "MainActivity".
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
This explanation part is also introduced at exit-an-android-app.