How to Call Activity from Fragment in Android

Last updated Apr 05, 2025

Android developers frequently need to navigate between application components. One of the most common scenarios is the need to call activity from fragment. If you're building multi-screen applications, understanding how to call activity from fragment in Android is essential for creating smooth user experiences.

In this comprehensive guide, we'll explore multiple approaches to start activity from fragment, providing clear code examples and practical solutions for common scenarios. Whether you're a beginner or experienced developer, this guide will help you master the techniques to call activity from fragment effectively.

Understanding Activities and Fragments

Before diving into how to call activity from fragment in Android, let's clarify the relationship between these components:

  • Activities: Complete screens in your Android application
  • Fragments: Modular UI components that live within activities

When you need to call activity from fragment, you're essentially transitioning from a UI component to a new full screen. Let's explore the various methods to start activity from fragment.

Basic Method: Using Intent to Call Activity from Fragment

The most straightforward approach to call activity from fragment in Android is using the Intent class. This is the foundation of navigation in Android applications

public void openNewActivity() {
    // Get context from the fragment's activity
    Intent intent = new Intent(getActivity(), DestinationActivity.class);
    startActivity(intent);
}

 

When you call activity from fragment using this method, you're leveraging the fragment's connection to its host activity. The getActivity() method returns the activity associated with the fragment, which provides the necessary context to start activity from fragment.

Passing Data When You Call Activity from Fragment

Often when you need to start activity from fragment, you'll want to transfer data to the new activity. Here's how to call activity from fragment while passing information:

public void openActivityWithData() {
    // Create intent to call activity from fragment
    Intent intent = new Intent(getActivity(), DestinationActivity.class);
    
    // Add data to pass when you start activity from fragment
    intent.putExtra("USER_ID", userId);
    intent.putExtra("USER_NAME", userName);
    
    // Call activity from fragment with the data
    startActivity(intent);
}

In the destination activity, retrieve the data:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_destination);
    
    // Get data that was passed when call activity from fragment occurred
    Intent intent = getIntent();
    int userId = intent.getIntExtra("USER_ID", -1);
    String userName = intent.getStringExtra("USER_NAME");
    
    // Use the data
}

 

Using StartActivityForResult to Get Data Back

Sometimes when you call activity from fragment, you need the new activity to return results. Here's how to start activity from fragment and receive data back:

private static final int REQUEST_CODE = 1001;

public void openActivityForResult() {
    // Prepare to call activity from fragment
    Intent intent = new Intent(getActivity(), InputActivity.class);
    
    // Start activity from fragment with request code
    startActivityForResult(intent, REQUEST_CODE);
}

// Handle the result after you call activity from fragment
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    
    if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
        // Process data returned after call activity from fragment
        String result = data.getStringExtra("RESULT_KEY");
        // Use the result data
    }
}

 

Modern Approach: Using Jetpack Navigation Component

The Android Jetpack Navigation component offers a more modern way to call activity from fragment:

// Define navigation action in your navigation graph XML

// Then in your fragment:
private fun navigateToDestination() {
    // Use Navigation component to call activity from fragment
    val navDirections = CurrentFragmentDirections.actionCurrentFragmentToDestinationActivity()
    findNavController().navigate(navDirections)
}

 

This approach makes it easier to visualize and manage how to call activity from fragment in Android through a navigation graph.

Safe Ways to Start Activity from Fragment

When implementing code to call activity from fragment, you should handle potential issues:

public void safelyStartActivity() {
    Activity activity = getActivity();
    if (activity != null && isAdded()) {
        // Safe to call activity from fragment
        Intent intent = new Intent(activity, DestinationActivity.class);
        startActivity(intent);
    }
}

 

The isAdded() check confirms the fragment is currently attached to an activity before attempting to start activity from fragment.

Common Issues When Trying to Call Activity from Fragment

Null Context Exceptions

One frequent issue when you try to call activity from fragment occurs if the fragment is detached:

// PROBLEMATIC: May cause NullPointerException
private void problematicStartActivity() {
    // Attempt to call activity from fragment without checking
    Intent intent = new Intent(getActivity(), DestinationActivity.class);
    startActivity(intent);
}

// SAFE: Check before you call activity from fragment
private void safeStartActivity() {
    Context context = getActivity();
    if (context != null) {
        // Safe to call activity from fragment
        Intent intent = new Intent(context, DestinationActivity.class);
        startActivity(intent);
    }
}

Memory Leaks

Be cautious when storing references when you call activity from fragment:

// AVOID: Can cause memory leaks
private static Activity activityRef;

private void leakyWayToCallActivity() {
    activityRef = getActivity();
    Intent intent = new Intent(activityRef, DestinationActivity.class);
    startActivity(intent);
}

 

Best Practices to Call Activity from Fragment in Android

  1. Always check if the fragment is attached before you start activity from fragment
  2. Use the correct context when you call activity from fragment
  3. Consider using the Navigation Component for complex navigation
  4. Define constant keys for data passed when you call activity from fragment
  5. Handle lifecycle considerations when managing how to call activity from fragment in Android

Code Template to Call Activity from Fragment

Here's a reusable template to safely call activity from fragment:

/**
 * Utility method to safely call activity from fragment
 * @param fragmentActivity The target activity class
 * @param extras Optional bundle of extras to pass
 */
public void safelyStartActivityFromFragment(Class<?> fragmentActivity, Bundle extras) {
    Context context = getActivity();
    if (context != null && isAdded()) {
        Intent intent = new Intent(context, fragmentActivity);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivity(intent);
    }
}

 

Conclusion

Understanding how to call activity from fragment in Android is essential for effective app navigation. Whether you're using the traditional Intent approach or modern Navigation Component, knowing the proper techniques to start activity from fragment will help you build more robust applications.

By following the best practices outlined in this guide, you can safely and efficiently call activity from fragment while avoiding common pitfalls. Remember to always consider the fragment's lifecycle state before attempting to start activity from fragment to prevent crashes and maintain a smooth user experience.

Now you have all the tools you need to successfully call activity from fragment in Android for any application scenario.

 

Simple example to call Activity From Fagment

Let us say now we need to call an other activity from Fragment inside Home Activity.

So How will call the Second activity from this current fragment.

By using the below code we will call the activity from the fragment

Start Activity From Fragment Example

Step 1: Create An Android Project in Android studio
Step 2: Create Fragment with a Text button.

 

package com.rrtutors.activitycallfragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link HomeFragemnt} interface
* to handle interaction events.
* Use the {@link HomeFragemnt} factory method to
* create an instance of this fragment.
*/
public class HomeFragemnt extends Fragment {

    public HomeFragemnt() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home_fragemnt, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();

    }

}

xml file

 

xml version="1.0" encoding="utf-8"?>

   

 

Step 3: Add Fragment to MainActivity

To add fragment to activity in different ways
1) By Using Fragment Manager
2) By XML file fragment widget.

In this Example we will load the Fragment inside activity by XML file

 

xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

 <fragment
     android:id="@+id/fragment"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     class="com.rrtutors.activitycallfragment.HomeFragemnt"
     />
androidx.constraintlayout.widget.ConstraintLayout>

 

in the above xml code we added fragment class to the fragment widget by 

class="com.rrtutors.activitycallfragment.HomeFragemnt"

step 4: Create Second Activity

Step 5: Now its time to write code for call Activity from Fragment.
Just update Fragment class by below code.

 

Button btn=getView().findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent=new Intent(getActivity(),SecondActivity.class);
        startActivity(intent);
    }
});

Step 6: Run application.

Now you can call activity from fragment by press the button.

start activity from Fragment Android

Read How to call an Activity method from Fragment