Java – How do I open or start a fragment from another activity?

How do I open or start a fragment from another activity?… here is a solution to the problem.

How do I open or start a fragment from another activity?

From the adapter for RecyclerView

included in the activity, I’m trying to start a fragment when an element of RecyclerView is pressed, which is my code now:

@Override
public void onClick(View v) {
    Intent intent;

int position = getAdapterPosition();

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    String onoff = preferences.getString("it's", "");

if (onoff.equalsIgnoreCase("on")) {
        if (position == 0) {

CategoriesRecyclerView.fragSubreddit = "aww";

intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

if (position == 1) {

CategoriesRecyclerView.fragSubreddit = "food";

intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

if (position == 2) {

CategoriesRecyclerView.fragSubreddit = "funny";

intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

if (position == 3) {

CategoriesRecyclerView.fragSubreddit = "gaming";

intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

} else if (onoff.equalsIgnoreCase("off")) {

if (position == 0) {

CategoriesRecyclerView.fragSubreddit = "gaming";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

if (position == 1) {

CategoriesRecyclerView.fragSubreddit = "funny";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

if (position == 2) {

CategoriesRecyclerView.fragSubreddit = "food";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

if (position == 3) {

CategoriesRecyclerView.fragSubreddit = "aww";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }
    }
}

I

tested it to launch some of the “test activities” I created, so I know everything works fine except fragment launch.

The error is here:

intent = new Intent(context, MainFragment.class);
context.startActivity(intent);

I’m launching Fragment because it’s an Activity, so when I run the application it crashes and tells me to declare MainFragment as an Activity in my list.

How do I launch the fragment from my activity?

Thank you so much.

Solution

You can’t start a fragment with Intents, so I recommend it to you:

Fragment mFragment = null;
mFragment = new MainFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

For more information, see Fragments Transactions documents

Related Problems and Solutions