-2

I am calling some fragments from HomeScreen.java. Now whenever i press back button in any fragment, its closes the application. But i want previous fragment which was loaded.Following is HomeScreen.java code.

public class HomeScreen extends AppCompatActivity implements JobListFragment.OnJobSelectedListener {



    Timer timer;
    TimerTask timerTask;
    final android.os.Handler handler = new android.os.Handler();

    FragmentTransaction transaction;
    android.app.FragmentManager fragmentManager;
    ProfileFragment profileFragment;
    HomeFragment homeFragment;
    LocationFragment locationFragment;
    JobListFragment jobListFragment;
    JobDetailsFragment jobDetailsFragment;

    ActionBar actionBar;
    Toolbar toolbar;

    Fragment fragment;




    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homescreen);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        actionBar = getSupportActionBar();

        KitLocate.initKitLocate(HomeScreen.this, "f08fb7d8-bc35-46c6-aaad-07657eb4a59c");
        KitLocate.setUniqueUserID(HomeScreen.this, Utils.getUniqueId(HomeScreen.this));
        String onlineStatus = Utils.getStringPref(HomeScreen.this, Constants.onlineStatus);

        profileFragment =new ProfileFragment();
        homeFragment = new HomeFragment();
        locationFragment=new LocationFragment();

        jobListFragment = new JobListFragment();
        jobDetailsFragment = new JobDetailsFragment();
        fragmentManager =  getFragmentManager();
        transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.fragmentContainer, homeFragment);

        transaction.commit();




    }

    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, 1000, 10000); //
    }

    public void stoptimertask(View v) {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {
                        String locality = PeriodicHandler.getInstance().getLocality();
                        String subLocality = PeriodicHandler.getInstance().getSubLocality();

                        LocationFragment locationFrag = (LocationFragment)
                                getFragmentManager().findFragmentById(R.id.fragmentContainer);
                        /*if(locationFrag != null){
                            System.out.println();
                            locationFrag.updateLocationText();
                        }*/


                    }
                });
            }
        };
    }


    @Override
    public void onJObSelected(int position, String jobId) {
        fragmentManager =  getFragmentManager();
        transaction = fragmentManager.beginTransaction();
        jobDetailsFragment = new JobDetailsFragment();
        if(jobDetailsFragment.isAdded() || jobDetailsFragment.isHidden()){
            System.out.println("44444444444444444444");
            Bundle bundle = new Bundle();
            bundle.putString(Constants.jobID, jobId);
            jobDetailsFragment.setArguments(bundle);
            transaction.replace(R.id.fragmentContainer, jobDetailsFragment);
            transaction.addToBackStack(null);

        }else{


            Bundle bundle = new Bundle();
            bundle.putString(Constants.jobID, jobId);
            jobDetailsFragment.setArguments(bundle);
            transaction.add(R.id.fragmentContainer, jobDetailsFragment);//transaction.show(profileFragment);

        }
        transaction.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {

            case R.id.action_account:
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setHomeButtonEnabled(true);

                fragmentManager =  getFragmentManager();
                transaction = fragmentManager.beginTransaction();
                System.out.println("isadded"+profileFragment.isAdded()+"isHidden"+profileFragment.isHidden());
                if(profileFragment.isAdded() || profileFragment.isHidden()) {
                    /*transaction.show(profileFragment);
                    transaction.hide(locationFragment);*/
                    profileFragment = new ProfileFragment();
                    transaction.replace(R.id.fragmentContainer, profileFragment, LocationFragment.TAG);
                    transaction.addToBackStack("account");
                }else{
                    transaction.add(R.id.fragmentContainer, profileFragment);//transaction.show(profileFragment);
                }
                transaction.commit();
                break;
            case R.id.action_profile_location:
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setHomeButtonEnabled(true);

                fragmentManager =  getFragmentManager();
                transaction = fragmentManager.beginTransaction();
                System.out.println("isadded"+locationFragment.isAdded()+"isHidden"+locationFragment.isHidden());
                if(locationFragment.isAdded() || locationFragment.isHidden()) {
                    /*transaction.show(locationFragment);
                    transaction.hide(profileFragment);*/
                    locationFragment = new LocationFragment();
                    transaction.replace(R.id.fragmentContainer, locationFragment);
                    transaction.addToBackStack(null);
                }
                else{
                    transaction.add(R.id.fragmentContainer, locationFragment);//transaction.show(profileFragment);

                }
                transaction.commit();
                break;
            case R.id.action_profile_time:
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setHomeButtonEnabled(true);

                fragmentManager =  getFragmentManager();
                transaction = fragmentManager.beginTransaction();
                System.out.println("isadded" + jobListFragment.isAdded() + "isHidden" + jobListFragment.isHidden());
                if(jobListFragment.isAdded() || jobListFragment.isHidden()){
                    System.out.println("111111111111111111");
                    // transaction.show(jobListFragment);
                    jobListFragment = new JobListFragment();
                    transaction.replace(R.id.fragmentContainer, jobListFragment);
                    transaction.addToBackStack("profile");

                }else{
                    transaction.add(R.id.fragmentContainer, jobListFragment);//transaction.show(profileFragment);
                }
                transaction.commit();
                break;
            case android.R.id.home:
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(false);
                actionBar.setHomeButtonEnabled(false);
                fragmentManager =  getFragmentManager();
                transaction = fragmentManager.beginTransaction();
                System.out.println("isadded"+homeFragment.isAdded()+"isHidden"+homeFragment.isHidden());
                if(homeFragment.isAdded() || homeFragment.isHidden()){
                    System.out.println("55555555555555555");
                    //transaction.remove(homeFragment);
                    //transaction.add(R.id.fragmentContainer, homeFragment);
                    //transaction.show(homeFragment);
                    homeFragment = new HomeFragment();
                    transaction.replace(R.id.fragmentContainer, homeFragment);
                    transaction.addToBackStack("home");
                }else{
                    transaction.add(R.id.fragmentContainer, homeFragment);//transaction.show(profileFragment);
                }
                transaction.commit();
                break;

        }
        return true;
    }
   /*@Override
    public void onBackPressed() {
        if (getFragmentManager().popBackStackImmediate()) return;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
                finish();
        else
            finishAfterTransition();
    }*/

}

So i have three menu icons, i am loading fragments from menu clicks.So please let me know something i did wrong.

malli
  • 642
  • 2
  • 12
  • 30

2 Answers2

1

Suppose you have 3 fragments

(1) Fragment A

(2) Fragment B

(3) Fragment C

You are going A to B then B to C then Backpress will return to B then again Backpress will return to A then Backpress will close app.

Method for replace Fragment by adding Tag:

Pass your fragment and tag as arguments in below method.

private void replaceFragment(Fragment frag, String tag) {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.realtabcontent, frag);
    transaction.addToBackStack(tag);
    transaction.commitAllowingStateLoss();
}

No need to write onBackPress() or fragmentManager.popBackStack(), it will automatically handle.

Done

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
  • Hi hiren i replaced and edited my code with as you suggested.Now it is working fine.But some times it is crashing i dont know why it is can you tell me why it is happening..Mostly it is happening in Fragment B.. – malli Jun 11 '15 at 12:35
  • @malli, Can you please give me logcat ? – Hiren Patel Jun 11 '15 at 13:56
  • @malli, where you have posted logcat ? – Hiren Patel Jun 12 '15 at 04:10
  • I edited this post but it is displaying will be visible only to you until it is peer reviewed. – malli Jun 12 '15 at 04:12
  • @malli, I have checked logcat, your problem is in Fragment onCreateView(); you did something wrong there. – Hiren Patel Jun 12 '15 at 04:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/80344/discussion-between-hiren-patel-and-malli). – Hiren Patel Jun 12 '15 at 04:15
  • I already posted entire code in the question.Now just i modified that with replaceFragment().Can you check that once in the question please.. – malli Jun 12 '15 at 04:24
  • @malli, As I said problem is on onCreateView of Fragment, please post this code. – Hiren Patel Jun 12 '15 at 04:33
  • @malli, how can run fragment without onCreatView() method ? – Hiren Patel Jun 12 '15 at 04:49
  • @malli, you are replacing other fragment from onCreateView(), means you are going to A to B from A fragment's onCreateView(). please remove code. CustomMapFragment mapFragment = new CustomMapFragment(); FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); transaction.add(R.id.map_container, mapFragment).commit(); – Hiren Patel Jun 12 '15 at 05:02
  • Shall we continue discussion in chat hiren – malli Jun 15 '15 at 06:52
  • @malli, lets have discussion. – Hiren Patel Jun 15 '15 at 06:55
0

Add this

@Override
public void onBackPressed() {
   if (getFragmentManager().getBackStackEntryCount() > 0) {
       getFragmentManager().popBackStack();
   }
   else
   {
       super.onBackPressed;
   }
}
Hamilton
  • 152
  • 6
  • Are you sure that your cases add your fragments to backstack? Check that transaction.addToBackStack("fragment"); is used. – Hamilton Jun 11 '15 at 11:22
  • No i have not used that statement any where. I used transaction.addToBackStack(null) for LocationFragment. For remaining Fragments i have used transaction.addToBackStack(string) like this. – malli Jun 11 '15 at 11:30
  • If you use transaction.addToBackStack(null) the fragments are not entered in the backstack. Use transaction.addToBackStack(string) for fragments you want to have the functionality you describe. – Hamilton Jun 11 '15 at 11:35
  • I have editted my answer. It is getFragmentManager().popBackStack(); for your case. – Hamilton Jun 11 '15 at 11:43
  • Hamiltion i replaced getSupportFragmentManager().popBackStack(); to getFragmentManager().popBackStack(); in onBackPressed() but no luck. – malli Jun 11 '15 at 11:50
  • Hamilton and i tested it now again it is not working as expected.But it is working after loading three fragments one by one,after that only it displays previous fragment that also some times correct and some times not correct. – malli Jun 11 '15 at 12:01