0

hey guys Im trying to make an activity that has a one framelayout that changed when an Item in the drawer is selected, but my problem is when I rotate the screen the fragment that was replaced goes back to the previous fragment. ex. I opened the app and it shows me the fragment A then I try to select another fragment from the drawer which is fragment B but then when I try to rotate while Im on fragment B it goes back to fragment A. here is my code.

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

        initViews();

        passedFragment = this.getIntent().getExtras().getString("fragmentClass");

        if(savedInstanceState != null){
             getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);

        }
            switch (passedFragment){
                case "com.serverus.oom.fragments.FragmentAgency":
                    fragmentClass = FragmentAgency.class;

                    menuItemReserve = mMenu.findItem(R.id.agency_menu_item);
                    break;
                case "com.serverus.oom.fragments.FragmentServices2":
                    fragmentClass = FragmentServices2.class;
                    menuItemReserve = mMenu.findItem(R.id.services_menu_item);
                    break;
                case "com.serverus.oom.fragments.FragmentContactUs":
                    fragmentClass = FragmentContactUs.class;
                    menuItemReserve = mMenu.findItem(R.id.contact_menu_item);
                    break;
                default:
                    fragmentClass = FragmentAgency.class;
                    break;
            }
        fragmentReplace(fragmentClass);

}


 public void fragmentReplace(Class fragmentClass) {

        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = this.getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();

                ft.replace(R.id.flContent, fragment, FRAGMENT_TAG).addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).commit();


        }

thanks in advanced

alvin valdez
  • 161
  • 3
  • 13

3 Answers3

0

Use the setRetainInstance(true) in the fragment's on create. Refer to this question for further details - Further understanding setRetainInstance(true)

setRetainInstance(true) - should be mentioned in the onCreate() of the fragment activity.

Please also note

Note: Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it). There are three ways to provide an ID for a fragment:

•Supply the android:id attribute with a unique ID.

•Supply the android:tag attribute with a unique string.

•If you provide neither of the previous two, the system uses the ID of the container view.

This strongly implies that if you do setContentView(R.layout.whatever) in Activity.onCreated() and that layout contains a fragment with setRetainInstance(true), then when the activity is recreated it will be searched for again using its id or tag.

Community
  • 1
  • 1
Abhinav Arora
  • 537
  • 1
  • 7
  • 23
  • sorry for this newbie question but where can I put setRetainInstance(true)? because Im changing the fragment when I clicked on the drawer though the initial fragment inside the framelayout. – alvin valdez Jul 30 '15 at 08:34
  • Hope this helps ! (expanded the explaination) – Abhinav Arora Jul 30 '15 at 08:53
  • I tried putting it below setContentView(R.layout.activity_main); setRetainInstance(true); but it is now recognized and is the tag you are reffering to is this one getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG); – alvin valdez Jul 30 '15 at 08:56
  • Please not above - you have to put in the onCreate() of the fragment class – Abhinav Arora Jul 30 '15 at 08:57
  • tag, id refers to - android:tag or android:id which you mention in xml of the fragment like this – Abhinav Arora Jul 30 '15 at 09:03
  • still the same tho I put it on all of my fragment classes. please see: http://pastie.org/10319684 – alvin valdez Jul 30 '15 at 09:05
  • I have mentioned it more than 3 times. IT SHOULD BE MENTIONED IN THE **onCreate()** not onCreateView() – Abhinav Arora Jul 30 '15 at 09:07
  • still the same man, I think @uknowbigmams is right that the same fragment gets created because of MainActivity.java onCreate it always call the same fragment from passedFragment variable. is there any other place to put the switch statement for the initial fragment creation? – alvin valdez Jul 30 '15 at 09:26
  • 1
    Hey try this out - put the whole switch statement along with the last statement fragmentReplace(fragmentClass); inside an if condition if(savedInstanceState==null). I think this will do – Abhinav Arora Jul 30 '15 at 11:26
  • If the answer helped you please accept the answer and upvote it. This is how it is done here. If an answer helps you, you have go to do it ! :) – Abhinav Arora Jul 30 '15 at 16:27
0

Can you show all your code ? My help could be better..

Maybe its because you don't store the passedFragment in the saveInstance and when you rotate the screen the activity recreate itself, passedFragment contains null. so "FragmentAgency.class" (default value) will always be set when rotate.

This code:

passedFragment = this.getIntent().getExtras().getString("fragmentClass");

..return null, because you can only get "fragmentClass" value when the activity is create at startActivity(..).

Check: http://developer.android.com/training/basics/activity-lifecycle/recreating.html to see how to use activity state to save and load your activity data.

  • heres some of my code: http://pastie.org/10319718 the process is that i have a screedslider where I click a button that will direct me to mainactivity, content of it will be set accordingly if what is selected screenslider. – alvin valdez Jul 30 '15 at 09:34
  • Try this, paste this function in your mainActivity: `@Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putString("value", passedFragment); super.onSaveInstanceState(savedInstanceState); }` Then add: `passedFragment = savedInstanceState.getString("value");` on "if(savedInstanceState != null){...}" And retry your app – uknowbigmams Jul 30 '15 at 09:44
  • this is now my latest app: http://pastie.org/10319758 but then when I try to rotate im having an error: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference at com.serverus.oom.MainActivity.onCreate(MainActivity.java:62) which is the switch statement in onCreateView – alvin valdez Jul 30 '15 at 09:54
  • Can you check if savedInstanceState or passedFragment in if and else to see were is null. which line is the MainActivity.java:62 ? – uknowbigmams Jul 30 '15 at 11:58
0
private static String RUN_ONCE;

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


        initViews();

        passedFragment = this.getIntent().getExtras().getString("fragmentClass");

            switch (passedFragment){
                case "com.serverus.oom.fragments.FragmentAgency":
                    fragmentClass = FragmentAgency.class;

                    menuItemReserve = mMenu.findItem(R.id.agency_menu_item);
                    break;
                case "com.serverus.oom.fragments.FragmentServices2":
                    fragmentClass = FragmentServices2.class;
                    menuItemReserve = mMenu.findItem(R.id.services_menu_item);
                    break;
                case "com.serverus.oom.fragments.FragmentContactUs":
                    fragmentClass = FragmentContactUs.class;
                    menuItemReserve = mMenu.findItem(R.id.contact_menu_item);
                    break;
                default:
                    fragmentClass = FragmentAgency.class;
                    break;
            }

        if(savedInstanceState == null){
            fragmentReplace(fragmentClass);
        }else{
            getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
        }

    }


@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(RUN_ONCE, true);
    }
alvin valdez
  • 161
  • 3
  • 13