Android Build an Interactive Story App The Rest of the Story Maintaining a Custom Back Stack

Another way to navigate through the pages.

public void onBackPressed() {
        if (mPageStack.peek()==0){
        super.onBackPressed();}
        else {
            mPageStack.pop();
            loadPage(mPageStack.pop());
        }
    } 

What is happening here is: peek():Looks at the object at the top of this stack without removing it from the stack.

if (mPageStack.peek()==0){ super.onBackPressed();} == if (pageNumber 0 at the top of the stack) { execute the super method which takes us to the main activity }

else (if the top of the stack not the pagenumber 0) {lets say that you've got pages on stack like that >> 0 1 2 3 4

1-mPageStack.pop(); ==Remove last pagenumber which is "4" >> 0 1 2 3 .

2- loadPage(mPageStack.pop()); == Remove the last page again but before removing it load it first >> remove 3 but load it first so it's going to be like that>> 0 1 2 and since we have mPageStack.push() in the loadPage method, the pagenumber 3 will be added again>> 0 1 2 3 }

Also if you "PLAYED AGAIN" you'll still be going to the main page whenever you reach page 0 and press Back, instead of navigating through the previous story walkthrough pages. without doing clear stack as mentioned in the video thanks to peek()==o.

0 1 2 3 4 > PLAY AGAIN > 0 1 2 > BACK > 0 1 > BACK > 0 > BACK > main page.

hope you get it.

Ben Jakuben
Ben Jakuben
Treehouse Teacher

Very nice solution! I like that pressing back at page zero will always take you back to the title screen. I'm going to link to your post in the Teacher's Notes.

Ali Nawab
Ali Nawab
13,869 Points

If page 0 is never popped in the if block, doesn't this mean playing again will push an extra page 0 to the stack (stack >> 0 0) and therefore going back from page 0 will load the same page?

Kareem Jeiroudi
Kareem Jeiroudi
14,981 Points

I like your solution too. So as far as I understood and after trying out your solution, the difference is that yours 'peeks', whether the page number is 0, and if so it'll go back to the main title, instead of going back to previous page. In case where we would press PLAY AGAIN, the problem is that the stack already has {0, 2, 6} - if we kept pressing on the choice02, for instance. Now when pressed on PLAY AGAIN, page0 is going to load again and be pushed to the stack. Now you're on page0 and the stack looks like this {0, 2, 6, 0}. In Ben's solution: because the conditional is if (stack.isEmpty()) - but it's not - it'd direct you back to page6. However, instead it should take you back to the main title since you're on page0. And that's exactly what Tarek's solution does.

Thanks for sharing this!