Call Fragment method from Activity

18,981

Solution 1

That is because your order is wrong.

PlaceholderFragment fragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_grupos);

    if(savedInstanceState == null)
    {
        fragment = new PlaceHolderFragment();
        fragment.setTag(R.id.myfragmentId);
        getFragmentManager().beginTransaction()
            .add(R.id.container, fragment).commit();
    }
    else
    {
        if(fragment == null)
        {
            fragment = (PlaceholderFragment) getFragmentManager().findFragmentByTag(R.id.myfragmentId);
        }
    }
}

Solution 2

if your activty in not parent you can use this code :

final PlaceholderFragment pf = new PlaceholderFragment();
pf.your_method_name();

this code worked for me

Solution 3

I think you can try FragmentActivity as like- public class Grupos extends FragmentActivity because Base class for activities that want to use the support-based Fragment and Loader APIs. (android.support.v4.app.FragmentActivity)

Solution 4

Try to use FragmentActivity instead of Activity.

Then you should call getSupportFragmentManager instead of getFragmentManager

Also you can't pass a layout to findFragmentById method. you should give it a fragment id (R.id.FRAGMENT_ID) instead.

Try make it like this:

public class Grupos extends FragmentActivity {

PlaceholderFragment fragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_grupos);

    fragment = new PlaceholderFragment();
    getSupportFragmentManager().beginTransaction()
                .add(R.id.container, fragment).commit();
}

@Override
protected void onResume()
{
    super.onResume();
    Log.i("Test","Test");
    fragment.myOnResume();
}
Share:
18,981
carlosdiazp
Author by

carlosdiazp

C# .NET and Android Software Engineer.

Updated on June 04, 2022

Comments

  • carlosdiazp
    carlosdiazp almost 2 years

    I need to call a method inside a fragment in onResume activity, but always shows FC with this error:

    06-15 14:59:58.496: E/AndroidRuntime(28904): FATAL EXCEPTION: main
    06-15 14:59:58.496: E/AndroidRuntime(28904): Process: com.carlosdiaz.tfm_usuarios, PID: 28904
    06-15 14:59:58.496: E/AndroidRuntime(28904): java.lang.RuntimeException: Unable to resume activity {com.carlosdiaz.tfm_usuarios/com.carlosdiaz.tfm_usuarios.Grupos}: java.lang.NullPointerException
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2774)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2803)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2238)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.os.Handler.dispatchMessage(Handler.java:102)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.os.Looper.loop(Looper.java:136)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.app.ActivityThread.main(ActivityThread.java:5001)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at java.lang.reflect.Method.invokeNative(Native Method)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at java.lang.reflect.Method.invoke(Method.java:515)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at dalvik.system.NativeStart.main(Native Method)
    06-15 14:59:58.496: E/AndroidRuntime(28904): Caused by: java.lang.NullPointerException
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at com.carlosdiaz.tfm_usuarios.Grupos.onResume(Grupos.java:52)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.app.Activity.performResume(Activity.java:5310)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2764)
    06-15 14:59:58.496: E/AndroidRuntime(28904):    ... 12 more
    

    I don't know what can I do.

    This is mi OnCreate & onResume methods:

    public class Grupos extends Activity {
    
        PlaceholderFragment fragment;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_grupos);
    
            fragment = (PlaceholderFragment) getFragmentManager().findFragmentById(R.layout.fragment_grupos);
    
            if (savedInstanceState == null) {
                getFragmentManager().beginTransaction()
                        .add(R.id.container, new PlaceholderFragment()).commit();
            }
        }
    
        @Override
        protected void onResume()
        {
            super.onResume();
            Log.i("Test","Test");
            fragment.myOnResume();
        }
    

    ...

    My method is inside the Fragment class:

    public static class PlaceholderFragment extends Fragment {
    ...
    public void myOnResume() {
                GruposTask getGrupos = new GruposTask(PlaceholderFragment.this, getActivity());
                getGrupos.execute(id);
            }
    ...
    

    Thank You in advance!

    edit:

    now im trying to create the fragment in the activity xml to call it later from oncreate() this way:

    PlaceholderFragment mainFragment = (PlaceholderFragment)getFragmentManager().findFragmentById(R.id.listGroup);
    

    this is the activity layout:

       xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.carlosdiaz.tfm_usuarios.Grupos"
        tools:ignore="MergeRootFrame">
        <fragment class="com.carlosdiaz.tfm_usuarios.Grupos.PlaceholderFragment"
                android:id="@+id/listGroup"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent" />
     </FrameLayout>
    

    But now Im having this error:

    06-15 19:20:15.956: E/AndroidRuntime(7424): FATAL EXCEPTION: main
    06-15 19:20:15.956: E/AndroidRuntime(7424): Process: com.carlosdiaz.tfm_usuarios, PID: 7424
    06-15 19:20:15.956: E/AndroidRuntime(7424): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carlosdiaz.tfm_usuarios/com.carlosdiaz.tfm_usuarios.Grupos}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.os.Handler.dispatchMessage(Handler.java:102)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.os.Looper.loop(Looper.java:136)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.ActivityThread.main(ActivityThread.java:5001)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at java.lang.reflect.Method.invokeNative(Native Method)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at java.lang.reflect.Method.invoke(Method.java:515)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at dalvik.system.NativeStart.main(Native Method)
    06-15 19:20:15.956: E/AndroidRuntime(7424): Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.Activity.setContentView(Activity.java:1929)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at com.carlosdiaz.tfm_usuarios.Grupos.onCreate(Grupos.java:39)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.Activity.performCreate(Activity.java:5231)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     ... 11 more
    06-15 19:20:15.956: E/AndroidRuntime(7424): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.carlosdiaz.tfm_usuarios.Grupos.PlaceholderFragment: make sure class name exists, is public, and has an empty constructor that is public
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.Fragment.instantiate(Fragment.java:597)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.Fragment.instantiate(Fragment.java:561)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.Activity.onCreateView(Activity.java:4778)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     ... 21 more
    06-15 19:20:15.956: E/AndroidRuntime(7424): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.carlosdiaz.tfm_usuarios.Grupos.PlaceholderFragment" on path: DexPathList[[zip file "/data/app/com.carlosdiaz.tfm_usuarios-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.carlosdiaz.tfm_usuarios-2, /vendor/lib, /system/lib]]
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     at android.app.Fragment.instantiate(Fragment.java:583)
    06-15 19:20:15.956: E/AndroidRuntime(7424):     ... 24 more
    
  • Mahmudul Haque Khan
    Mahmudul Haque Khan almost 10 years
    ok bro @carlosdiazp give me your project in my mail: [email protected] when I will be free then I solve your problem...
  • carlosdiazp
    carlosdiazp almost 10 years
    Now Im trying to give an Id to my fragment. to this, I create a fragment tag inside my activity (like this: <fragment android:name="com.carlosdiaz.tfm_usuarios.Grupos.Placeholder‌​Fragment" android:id="@+id/listGroup" ... ). But then, the error says 06-15 16:30:59.296: E/AndroidRuntime(24797): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.carlosdiaz.tfm_usuarios.Grupos.PlaceholderFragment" on path: DexPathList[[zip file "/data/app/com.carlosdiaz.tfm_usuarios-1.apk"],nativeLibrary‌​Directories=[/data/a‌​pp-lib/com.carlosdia‌​z.tfm_usuarios-1, /vendor/lib, /system/lib]]
  • carlosdiazp
    carlosdiazp almost 10 years
    I don´t think so because it continues giving error with null pointer. Also, Ive seen in Android fragment page, that I have to put R.id.fragmentId, not R.layout
  • carlosdiazp
    carlosdiazp almost 10 years
    my problem now is that I have a ForcedClose when I run, because Fragment in layouts didnt find the class name of the fragment & I dont know why
  • EpicPandaForce
    EpicPandaForce almost 10 years
    Change your package name so it doesn't have an underline in it. Also, make sure PlaceholderFragment is actually in its own class, and not inside the MainActivity as an inner static class.
  • carlosdiazp
    carlosdiazp almost 10 years
    Yeah, thats was the problem. I had my fragment class inside the activity, and obviously, static. Now, I create a new class with the fragment code and it works. Thank You Very Much ;). Greetings!!
  • CoDe
    CoDe over 9 years
    How can set fragment ID or Tag ?
  • EpicPandaForce
    EpicPandaForce over 9 years
    @shubh if I remember correctly, then the Fragments have a setTag() method. But you can also use its Id to find the fragment, which by default is set to be the same as the FrameLayout container that the fragment is loaded into.
  • CoDe
    CoDe over 9 years
    not it's not..but we can setTag while adding/replace with FragmentManager...thanks :)