Pressing back button from one activity refreshes previous activity in stack

12,878

Solution 1

The problem is with your override to the back press (which does not need to be overridden) and is likely a symptom of with what your activity does when focus returns to it.

Firstly if you don't override onBackPress the previous activity will load (that's the default behaviour because of the backstack) so you don't need to manually call it with a new intent and tell manually tell it to go to the previous activity.

When your parent activity (ClassActivity) then starts again it will go through the normal lifecycle - it will get resumed and all saved instance states get restored. Since you haven't posted it you need to make sure onResume and onRestart are not doing anything in your parent activity such as loading or setting data.

If you do keep the onBackPress you wrote then it will create a new instance and onCreate will always be called, unless it is singleInstance flagged, in which case onNewIntent will be called, but neither of these things seem to be what you want.

In response to your Edit 3 you need to make sure that LoadingPage has android:noHistory="true" so that it is not available to the backstack and then finish it explicitly to clean it up when you start the main class

That is a simple as calling finish when starting your intent

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        Intent mainIntent = new Intent(LoadingPage.this, ClassActivity.class);
        startActivity(mainIntent);
        finish(); //end the wrapping activity (LoadingPage)
    }
}, 1000);

The last thing you should be aware of is the difference between up and back navigation. In case you are navigating back via the home/up button you should also tell the manifest that these two activities are related. In the manifest entry for ClassActivityEdit you should add android:parentActivityName="com.teamtreehouse.oslist.ClassActivity"

Solution 2

Your Problem is so much strange ! just by not overriding OnBackPressed you will get the result you want. I guess the problem is in your manifest.

android:noHistory="true"

It doesn't let the activity to stay in history stack, try removing it. also try this:

android:launchMode="singleInstance"

By doing this, the activity wont become created again.

Solution 3

First of all there is no need of overriding onBackPressed(). As Doug mentioned the parent activity is below the child activity in the stack , so it would be visible just after the child activity finishes on back pressed.

There is a suggestion for you as the ActionBarActivity is deprecated so it would be better to extend the class AppCompatActivity in your activity class.

I have tried to replicate the issue but failed. So I have created a classes.

LandingPage.java

public class LandingPage extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.loading_page);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            startActivity(new Intent(LandingPage.this, ClassActivity.class));
        }
    }, 1000);
}

}

ClassActivity.java

public class ClassActivity extends AppCompatActivity {


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.class_activity);

    //Do whatever you want to  do

}
public void editListener(View v)
{
    Intent addNewClass = new Intent(ClassActivity.this,ClassActivityEdit.class);
    RelativeLayout buttonTableRow = (RelativeLayout) v.getParent();
    EditText getCourseID = (EditText) buttonTableRow.findViewById(R.id.courseNumberActivity);
    String courseIDString = getCourseID.getText().toString();
    addNewClass.putExtra("CourseIDString", courseIDString);
    startActivity(addNewClass);
}
}

ChildActivityEdit.java

public class ClassActivityEdit extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.class_activity_edit);
    String course_no = getIntent().getStringExtra("CourseIDString");
    Toast.makeText(ClassActivityEdit.this,course_no,Toast.LENGTH_SHORT).show();
    //Do whatever you want to  do

}
}

Solution 4

By default, Android will retain activities in a stack, so when you go from Activity A to Activity B, Activity A will be brought back when you finish Activity B unless you do some other stuff like mess with the launchMode, finish A on returning from B, etc.

From what can be seen in your code, your problem should be solved by not overriding onBackPressed() in your child activity. Also, you should remove your <intent-filter> block for the child activity in the manifest.

I recommend reading up on managing the activity lifecycle and tasks and back stack.

Solution 5

Just let the back button do what it normally does. Don't override it and don't start a new activity. The parent activity is below the child activity in the stack, so it should appear when the child activity finishes.

Share:
12,878

Related videos on Youtube

human
Author by

human

Updated on May 25, 2022

Comments

  • human
    human almost 2 years

    On pressing back button from child activity parent activity displays for a second and refreshes itself.

    In child activity I have this code in java file

    @Override
    public void onBackPressed()
    {
    
        Intent moveback =
                new Intent(ClassActivityEdit.this, ClassActivity.class);
        startActivity(moveback);
        finish();
    }
    

    ClassActivityEdit is child class. In manifest file code is as follows

    <activity android:name=".ClassActivity"
            android:label="Class Activity">
            <intent-filter>
                <action android:name="com.teamtreehouse.oslist.ClassActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    
        <activity android:name=".ClassActivityEdit"
            android:label="Class Activity"
            android:noHistory="true">
            <intent-filter>
                <action android:name="com.teamtreehouse.oslist.ClassActivityEdit" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    

    On back button I just want the ClassActivity layout to be displayed without it being refreshed.

    Edit: ClassActivityEdit doesnt extend ClassActivity. Its just that some button press in ClassActivity will result in opening ClassActivityEdit.

    Edit2

    the below code in ClassActivity starts ClassActivityEdit

    public void editListener(View v) {
            Intent addNewClass =
                    new Intent(ClassActivity.this, ClassActivityEdit.class);
            RelativeLayout buttonTableRow = (RelativeLayout) v.getParent();
            TextView getCourseID = (TextView) buttonTableRow.findViewById(R.id.courseNumberActivity);
            String courseIDString = getCourseID.getText().toString();
            Bundle bundle = new Bundle();
    
            //Add your data to bundle
            bundle.putString("CourseIDString", courseIDString);
    
            addNewClass.putExtras(bundle);
            startActivity(addNewClass);
    }
    

    Edit 3: I also have a Landing (MAIN) activity which flashes for a second. On pressing back button from ClassActivityEdit activity Landing activity flashes again and then the ClassActivity activity loads. Finding it a bit tricky to solve.

    public class LoadingPage extends ActionBarActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading_page);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent mainIntent = new Intent(LoadingPage.this, ClassActivity.class);
                startActivity(mainIntent);
            }
        }, 1000);
    }
    

    }

    • Arpit Patel
      Arpit Patel about 8 years
      remove the onBackPressed() method and try it
    • human
      human about 8 years
      @ArpitPatel no it didnt work
    • Arpit Patel
      Arpit Patel about 8 years
      Can you provide some more code?? any why you use two intent-filter ??
    • human
      human about 8 years
      @ArpitPatel added the code which leads to ClassActivityEdit
    • Omid Heshmatinia
      Omid Heshmatinia about 8 years
      what do you mean by Back Button ?! Hardware back button or the one in Action bar ?! @human
    • Istiyak
      Istiyak about 8 years
      I think this can be helpfull for you :) stackoverflow.com/questions/5545217/…
    • vl4d1m1r4
      vl4d1m1r4 about 8 years
      Are your parent and child activity using different orientation? If so please have a look at Android: avoid calling onCreate() when back from another activity
  • Doug Stevenson
    Doug Stevenson about 8 years
    My answer stays the same. Normally you don't override onBackPressed and instead allow the back button to finish the current activity and remove it from the stack.
  • human
    human about 8 years
    I have a overrided onbackpressed method in ClassAcivity. But I tried your solution, still the screen is refreshing
  • Nick Cardoso
    Nick Cardoso about 8 years
    It wont be created, but it will still call onNewIntent. This however is fixing a symptom and not addressing the problem (that there is an intent requesting an instance)
  • Omid Heshmatinia
    Omid Heshmatinia about 8 years
    dear Nick, would you please share your manifest code for your LoadingPage and also the LoadingPage activity code ? what the user press backbutton, there is no ClassActivityEdit because you enabled NOHISTORY for it, so the user return to the LoadingPage Again. if the Loading page become created again, the user will be redirected to ClassActivity Again. @NickCardoso
  • Nick Cardoso
    Nick Cardoso about 8 years
    Edit would be the class he is leaving, but you really seem to be guessing about what these flags do.
  • human
    human about 8 years
    tried this but could you but on debugging it enters the onactivityresult and goes back to previous activity
  • rushabhshah1693
    rushabhshah1693 about 8 years
    You can just flash your landing activity in child's back pressed/on destroy and the classactivity would still be there, giving you the desired result. Sorry, forgot to mention this part.