Problems with the backstack feature

I am working on my MainActivity.java class and trying to implement backstack for navigating between fragments and activity. Even after using addToBackStack(null) and popbackStack0, I am facing issues with the functionality.

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //ImageView imageView=(ImageView) findViewById(R.id.mainpage);
        //imageView.setImageResource(R.drawable.banner);

       Button button1 = (Button) findViewById(R.id.cropbutton);
        button1.setOnClickListener(this);
        Button button2 = (Button) findViewById(R.id.diseasebutton);
        button2.setOnClickListener(this);
        Button button3 = (Button) findViewById(R.id.pestbutton);
        button3.setOnClickListener(this);
        Button button5 = (Button) findViewById(R.id.expertbutton);
        button5.setOnClickListener(this);



        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }
    //boolean doubleBackToExitPressedOnce = false;

    @Override
    public void onBackPressed()
    {


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        Button button1 = (Button) findViewById(R.id.cropbutton);
        Button button2 = (Button) findViewById(R.id.diseasebutton);
        Button button3=(Button) findViewById(R.id.pestbutton);
        Button button5 = (Button) findViewById(R.id.expertbutton);
        if (id == R.id.nav_camera) {
            Cropfragment cropfragment=new Cropfragment();
            FragmentManager manager=getSupportFragmentManager();
            manager.beginTransaction().replace(R.id.relative1,cropfragment,cropfragment.getTag()).addToBackStack(null).commit();
            manager.popBackStack("relative1",0);

        } else if (id == R.id.nav_gallery) {
            BlankFragment blankFragment=new BlankFragment();
            FragmentManager manager=getSupportFragmentManager();
            manager.beginTransaction().replace(R.id.relative1,blankFragment,blankFragment.getTag()).addToBackStack(null).commit();
            manager.popBackStack("relative1",0);

        }  else if (id == R.id.nav_home) {
            Intent appInfo = new Intent(MainActivity.this, MainActivity.class);
            startActivity(appInfo);

        } else if (id == R.id.nav_pesti) {
            pest blankFragment=new pest();
            FragmentManager manager=getSupportFragmentManager();
            manager.beginTransaction().replace(R.id.relative1,blankFragment,blankFragment.getTag()).addToBackStack(null).commit();
            manager.popBackStack("relative1",0);

        }
        else if (id == R.id.nav_expert) {

            Intent appInfo = new Intent(MainActivity.this, detail_expert.class);

            startActivity(appInfo);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    @Override
    public void onClick(View v) {
        Button button1 = (Button) findViewById(R.id.cropbutton);
        Button button2 = (Button) findViewById(R.id.diseasebutton);
        Button button3=(Button) findViewById(R.id.pestbutton);
        Button button5 = (Button) findViewById(R.id.expertbutton);
        switch (v.getId()) {

            case R.id.cropbutton:
                Cropfragment cropfragment = new Cropfragment();
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().replace(R.id.relative1, cropfragment, cropfragment.getTag()).addToBackStack(null).commit();
                manager.popBackStack("relative1", 0);
                break;

            case R.id.diseasebutton:
                BlankFragment blankFragment= new BlankFragment();
                FragmentManager manager1 = getSupportFragmentManager();
                manager1.beginTransaction().replace(R.id.relative1,blankFragment,blankFragment.getTag()).addToBackStack(null).commit();
                manager1.popBackStack("relative1",0);
                break;

            case R.id.pestbutton:
                pest pestFragment= new pest();
                FragmentManager manager2 = getSupportFragmentManager();
                manager2.beginTransaction().replace(R.id.relative1,pestFragment,pestFragment.getTag()).addToBackStack(null).commit();
                manager2.popBackStack("relative1",0);
                break;

            case R.id.expertbutton:
                Intent appInfo1 = new Intent(MainActivity.this, detail_expert.class);
                startActivity(appInfo1);
                break;

            default:
                break;
        }

    }

}

Answer №1

After reviewing the code, it seems like there might be some confusion on how to navigate. By using addBackStack with a tag instead of null and removing with the tag as well

manager.popBackStack("relative1",0);
. Alternatively, you can simply use popBackStack() or if you prefer using onBackPressed(), you will need to override the method, determine the fragment size, and pop them one by one in the activity.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method to update the title dynamically in the view page source?

I've set the default $document[0].title = "My App". In the HTML, by using <title ng-bind="title"></title>, it will show up on the tab header as "My App" However, if you right click on the page and choose "view page source", it still displ ...

An error message is displayed when attempting to retrieve a json response

After implementing my flask app, I noticed that the following code snippet is being returned: return json.dumps({'status': 'OK','url': 'www.blahg.com'}) Upon inspecting my javascript code, I found it to be structur ...

What is the best way to extract data from a nested array within an array of objects and transfer it to a separate array without altering its nested arrangement?

I have a collection of different objects stored in an array. Each object within the main array contains another array with specific details like this: const data = [ { id: 1, name: "Jack", interests: [ ...

Struggling to make AdMob function on Android: Error Code 0

I am really struggling with this issue. I followed the instructions provided by Google on their AdMob quick start page (https://developers.google.com/admob/android/quick-start), but unfortunately, it did not work as expected. Below is the code snippet from ...

Executing functions on Angular scope within Underscore Template

Having an underscore template being invoked from an Angular controller, there is a dropdown in the template and an onchange function called on the dropdown. Despite several attempts to get the method triggered in the onchange event, using this code <se ...

"Using SetState frequently results in multiple rerenders of the component

Currently, I am developing a messenger application with a main screen component that displays all messages. My goal is to make sure that whenever a user sends or receives a message, the component updates the Flatlist to show the latest sent message. To ach ...

Tips for maintaining the browser scroll bar at the top when switching routes in AngularJS

How can I ensure that the scrollbar is always at the top when a user is redirected to a different page after scrolling down on the home page? The autoscroll feature in the code below doesn't seem to be working. Any suggestions would be greatly appreci ...

Ways to display one element while concealing it when another is clicked

I am utilizing a series of div elements that can be triggered with the following code snippet: $(".course_id").on("click", function(){ var id = $(this).data("id"); $("div#lessons_by_course_" + id).removeClass("hidden"); }); The ...

Obtain a pointer to the timestamp within a embedded Kibana chart on an HTML webpage

The image at the specified link shows a black box labeled @timestamp displaying date and time information. Unfortunately, viewing the image requires a reputation of 10. Link to image: https://www.elastic.co/assets/bltde09cbafb09b7f08/Screen-Shot-2014-09-3 ...

Using React to integrate Zurb Foundation's slider by binding moved.zf.slider

Update: I have included the complete code as requested. There are a few modifications from the original version. I am attempting to integrate the foundation slider with react and ES6. The slider is supposed to trigger an event named moved.zf.slider when i ...

Having difficulty finding a specific Span element using Selenium WebDriver in Java

After being recorded in Selenium IDE, the output is as follows: click //span[@id='some_text']/table/tbody/tr/td/table/tbody/tr[2]/th/hd/font/span/acronym In my Eclipse entry using WebDriver (Java), it looks like this: driver.findElement( ...

How can timestamps be set in MongoDB during an insertOne() operation without relying on new Date() as in PostgreSQL's NOW()?

timestamp: { $currentDate: { $type: "timestamp" } } }); The insert() method is not functioning properly Is there anyone who can assist me with this issue? ...

What is the largest quantity of elements that can be stored in a JSONArray in GWT?

In my GWT application, I have a JSONArray object where I process input strings and manipulate files to insert elements based on conditions. When inserting a large number of elements into the JSONArray, I encounter the following exception: RangeError: Max ...

Implement Meteor authentication with Google OAuth

I'm attempting to set up a basic login button for my Meteor app using google oauth. I followed these steps: mrt create accounts mrt add accounts-google mrt add accounts-ui I removed the default html/css/js files and instead added: client/index.html ...

Initiating a server call to fetch data using jQuery's AJAX function

I need to create a simple AJAX request to check if a username already exists in the database. The challenge lies in the JavaScript function that sends the request: function usernameCheck(){ $.post("http://example.com/signup", {username: $("#username"). ...

steps for adding text to the header with selenium webdriver

I came across the following code snippet: <body> <table> <tr> <td style= "width:30%;"> <img class = "new" src="images/new-icon.png"> <td> <h1>Hello there!</h1> ...

What could be causing this JavaScript to output undefined?

const urls = [ "http://x.com", "http://y.com", "http://z.com", ]; for (let j=0; j<urls.length; j++) { setTimeout(function() { console.log(urls[j]); }, 3000); } I'm inserting this code snippe ...

Creating an HTML Table with Database Data utilizing JSP, Java, and JavaScript

Challenge: I am currently tasked with developing a web application for a university course using JSP, Java, Javascript, and JQuery without relying on any external frameworks or libraries. The main goal is to create a calendar-like table that displays cours ...

How to disable scrolling for React components with CSS styling

When incorporating a React component into my HTML, I follow this pattern: <html> <body> <div id=app>${appHtml}</div> <script src="/bundle.js"></script> </body> </html> Within my application, th ...

What sets apart "import { pick } from 'lodash';" from "import pick from 'lodash/pick';"?

Can you explain the difference between import { pick } from 'lodash'; and import pick from 'lodash/pick'; (Keep in mind that it's 'lodash/pick' in the second one, not just 'lodash'.) How do they each impact ...