Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android.support.v4.app.getFragmentManager() returns null?

This is my Stacktrace:

FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.test.fragments.LoadingFragment$1.run(LoadingFragment.java:66)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)

Line 66 of my Fragment:

FragmentTransaction ft = fm.beginTransaction();

fm is gotten like this:

android.support.v4.app.FragmentManager fm = getFragmentManager();

My Fragment extends android.support.v4.app.Fragment, these are my imports:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

i never had seen that i got null for a FragmentManager anybody got an Idea?

like image 624
Yalla T. Avatar asked Feb 18 '13 10:02

Yalla T.


2 Answers

Replace this getFragmentManager() with this getSupportFragmentManager() and also make sure that your activity extends FragmentActivity

like image 188
Pragnani Avatar answered Nov 13 '22 11:11

Pragnani


From android.support.v4.app.Fragment source:

// The fragment manager we are associated with.  Set as soon as the
// fragment is used in a transaction; cleared after it has been removed
// from all transactions.
FragmentManagerImpl mFragmentManager;

Apparently getFragmentManager() returns support version of fragment manager but only during a transaction (or parent fragment's child fragment manager).

I'm going to use this:

public FragmentManager getHostFragmentManager() {
    FragmentManager fm = getFragmentManager();
    if (fm == null && isAdded()) {
        fm = ((AppCompatActivity)getActivity()).getSupportFragmentManager();
    }
    return fm;
}
like image 4
Eugen Pechanec Avatar answered Nov 13 '22 11:11

Eugen Pechanec