Java – The problem of getting a FragmentTransaction from an activity when using compatibility

The problem of getting a FragmentTransaction from an activity when using compatibility… here is a solution to the problem.

The problem of getting a FragmentTransaction from an activity when using compatibility

So I’m working on a project that I want to run on an older Android device, so I use the compatibility library. I’m using an interface similar to NewsReader, except that the two fragments are not in an activity, but embedded in another fragment, which in turn is embedded in ViewPagger.

For simplicity, we’ll use these terms….

Activity -> ViewPager -> ContainerFragment->Fragment1
                                          ->Fragment2

In ContainerFragment,

I tried to replace fragment 1 with fragment 2 if it was a phone, so I tried the following code in ContainerFragment….

import android.support.v4.app.FragmentTransaction;    
...
public void onBarSelected(Integer index) {
    selectedBarIndex = index;
    if (isDualPane) {
         display it on the article fragment
        mBarEditFragment.displayBar(index);
    }
    else {
         use separate activity
        FragmentActivity activity = (FragmentActivity)getActivity();
        FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        ft.replace(R.id.bar_container, new BarEditFragment(),R.id.bar_edit);
    }

}

But I get the following compilation error

Type mismatch: cannot convert from android.app.FragmentTransaction 
 to android.support.v4.app.FragmentTransaction

I double-checked and the activity did extend the compatibility of FragmentActivity.

Update

Trying to change to….

And then get….

MainActivity activity = (MainActivity)getActivity();
Object test = activity.getFragmentManager().beginTransaction();
FragmentTransaction ft = (FragmentTransaction)test;
ft.replace(R.id.bar_container, new BarEditFragment());

I got….

java.lang.ClassCastException: android.app.BackStackRecord cannot be cast to android.support.v4.app.FragmentTransaction

Any ideas?

Answer:

I came up with my problem and the problem is that you shouldn’t get the fragment manager from the activity, but you should get it from the fragment.

This works….

public void onBarSelected(Integer index) {
    selectedBarIndex = index;
    if (isDualPane) {
         display it on the article fragment
        mBarEditFragment.displayBar(index);
    }
    else {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.bar_container, new BarEditFragment());
        ft.commit();
    }

}

Solution

Using

solves the same problem

getSupportFragmentManager()

Thanks

Related Problems and Solutions