Try to replace a fragment with another

advertisements

I need to replace a fragment with another at an onItemClick method. This is what I am trying:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        TipoRestaurante rteActual = (TipoRestaurante) adapter.getItem(position);
        String msg = "Has elegido el tipo " + rteActual.getNombre_tipo();
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();

        Fragment newFragment = new TabFragmentComer();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();

        transaction.replace(R.id.containerView, newFragment);
        transaction.addToBackStack(null);

        transaction.commit();

    }

But I am getting an exception:

09-28 23:51:02.310  14895-14895/com.solinpromex.elpasojuarezexperience E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.solinpromex.elpasojuarezexperience, PID: 14895
    java.lang.IllegalArgumentException: No view found for id 0x7f0d009b (com.solinpromex.elpasojuarezexperience:id/containerView) for fragment TabFragmentComer{42909b40 #1 id=0x7f0d009b}
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
            at android.os.Handler.handleCallback(Handler.java:808)
            at android.os.Handler.dispatchMessage(Handler.java:103)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
            at dalvik.system.NativeStart.main(Native Method)

I am arriving to the current fragment from an activity, like this:

if (menuItem.getItemId() == R.id.nav_item_comer) {
                     FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                     xfragmentTransaction.replace(R.id.containerView,new TabFragmentComerTiposRestaurante()).commit();
                 }

Any help is welcome

EDIT: MainActivity xml layout:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/rojomodesto"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:title="El Paso - Juárez Experience" />

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:id="@+id/drawerLayout"
        >

    <FrameLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/containerView">
     </FrameLayout>

    <android.support.design.widget.NavigationView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/shitstuff"
        app:itemTextColor="@color/black"
        app:menu="@menu/drawermenu"
        android:layout_marginTop="-24dp"
        />

    </android.support.v4.widget.DrawerLayout>

    </LinearLayout>


Your fragment should have an interface in it as follows:

public class MyFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    public MyFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = ...;
        return view;
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        TipoRestaurante rteActual = (TipoRestaurante) adapter.getItem(position);
        String msg = "Has elegido el tipo " + rteActual.getNombre_tipo();
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();

        Fragment newFragment = new TabFragmentComer();    

        if(mListener != null){
            mListener.onFragmentInteraction(newFragment);
        }

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Fragment fragment);
    }

}

Your activity should implement that interface:

MyActivity extends Activity implements OnFragmentInteractionListener{
//your activity methods...

@Override
    public void onFragmentInteraction(Fragment fragment) {
         //here you have that fragment and can change it with transactions
         FragmentTransaction transaction = getFragmentManager().beginTransaction();

        transaction.replace(R.id.containerView, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
}


To pass objects to the other fragment:

If the fragment is just the fragment you are creating above as newFragment you can add arguments to it as follows:

Fragment newFragment = new TabFragmentComer();
Bundle args = new Bundle();
args.putInt("myIntLabel", 2);
args.putString("myStringLabel", "my sample string");
//and you can add all you want to that bundle like this
newFragment.setArguments(args);

Then in your fragment onCreateView or onCreate method you can get that bundle like this:

...
Bundle args = getArguments();
int myInt = args.getInt("myIntLabel", (int defaultValue)); // returns 2
int myString  = args.getString("myStringLabel", (String defaultString)); // returns "my sample string"

And if you are not creating your fragment in this fragment you can add another argument to that interface method as Bundle args and add that bundle to your fragment where you create like this: fragment.setArguments(args)