Programmatically adding fragment to framelayout in android-ThrowExceptions

Exception or error:

I am trying to build a UI combining both static and dynamic elements. For this, I have divided my activity into fragments – all app navigation is then done by replacing fragments instead of navigating between activities.

In my main activity layout, I am using a FrameLayout:

        android:layout_above="@id/lowersection" />

I have a fragment declared as such:

public class MyFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragmentlayout, container, false);

Then, in my main activity (which extends FragmentActivity and uses the import, I am attempting to load this fragment into the frame layout.

MyFragment myf = new MyFragment();

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(, myf);

I have followed this from many other examples, however I am receiving a compiler error on the transaction.add() command, which nobody else seems to have encountered.

The error I am receiving is: The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, MyFragment).

Why is this? The MyFragment class extends Fragment so I would’ve thought this would work. What am I doing wrong?

Edit: The imports for my main activity are:

import org.joda.time.DateTime;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
How to solve:

Check your imports. Use instead of

Furthermore be sure you are using and calling getSupportFragmentManager(). It’s easy to miss this calls / imports. Thx to saiful103a with the hint of the FragmentManager.

Leave a Reply

Your email address will not be published. Required fields are marked *