我有一个片段(F1)与这样的公共方法

public void asd() {
    if (getActivity() == null) {
        Log.d("yes","it is null");
    }
}

是的,当我调用它(从活动),它是空…

FragmentTransaction transaction1 = getSupportFragmentManager().beginTransaction();
F1 f1 = new F1();
transaction1.replace(R.id.upperPart, f1);
transaction1.commit();
f1.asd();

一定是我做错了什么,但我不知道是什么。


Commit调度事务,也就是说,它不会立即发生,而是在下一次主线程准备就绪时在主线程上进行调度。

我建议加一个

onAttach(Activity activity)

方法,并在它上面放一个断点,看看它什么时候相对于你对asd()的调用被调用。您将看到它在您调用asd()退出的方法之后被调用。onAttach调用是片段附加到其活动的地方,从这一点上getActivity()将返回非空(注意还有一个onDetach()调用)。


在commit()之后调用回调函数的顺序:

无论你在commit()之后手动调用什么方法 onAttach () onCreateView () onActivityCreated ()

我需要做一些涉及一些视图的工作,所以onAttach()不适合我;它坠毁。所以我移动了我的代码的一部分,设置一些参数在一个方法调用后立即提交()(1.),然后在onCreateView()(3.)内处理视图的代码的另一部分。


PJL是对的。 我采纳了他的建议,我是这样做的:

为fragment定义的全局变量: attachingActivityLock = new Object(); private boolean syncVariable = false; 实现

@Override onAttach(Activity Activity) { super.onAttach(活动); synchronized (attachingActivityLock) { syncVariable = true; attachingActivityLock.notifyAll (); } }

3.我在线程中包装了我的函数,在那里我需要调用getActivity(),因为如果它将在主线程上运行,我将用步骤4阻塞线程。onAttach()将永远不会被调用。

    Thread processImage = new Thread(new Runnable() {

        @Override
        public void run() {
            processImage();
        }
    });
    processImage.start();

4所示。在我的函数中,我需要调用getActivity(),我使用这个(在调用getActivity()之前)

    synchronized (attachingActivityLock) {
        while(!syncVariable){
            try {
                attachingActivityLock.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

如果你有一些UI更新,记得在UI线程上运行它们。我需要更新ImgeView,所以我做了:

image.post(new Runnable() {

    @Override
    public void run() {
        image.setImageBitmap(imageToShow);
    }
});

最好的办法是在onAttach被调用时保持活动引用,并在任何需要的地方使用活动引用。

@Override
public void onAttach(Context context) {
    super.onAttach(activity);
    mContext = context;
}

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

这发生在您在另一个线程中调用getActivity()时,该线程在片段被删除后结束。典型的情况是在HTTP请求完成时调用getActivity()(例如Toast)(例如onResponse)。

为了避免这种情况,您可以定义一个字段名mActivity,并使用它来代替getActivity()。该字段可以在Fragment的onAttach()方法中初始化,如下所示:

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

    if (context instanceof Activity){
        mActivity =(Activity) context;
    }
}

在我的项目中,我通常用这个特性为我所有的Fragments定义一个基类:

public abstract class BaseFragment extends Fragment {

    protected FragmentActivity mActivity;

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

    if (context instanceof Activity){
        mActivity =(Activity) context;
    }
}
}

快乐的编码,


自Android API级别23起,onAttach(Activity Activity)已弃用。你需要使用onAttach(Context Context)。http://developer.android.com/reference/android/app/Fragment.html onAttach (android.app.Activity)

Activity是一个上下文,所以如果你可以简单地检查上下文是否是一个Activity,并在必要时强制转换它。

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

    Activity a;

    if (context instanceof Activity){
        a=(Activity) context;
    }

}

请按照以下步骤操作。我想这会对你有帮助。

private boolean isVisibleToUser = false;
private boolean isExecutedOnce = false;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_my, container, false);
    if (isVisibleToUser && !isExecutedOnce) {
        executeWithActivity(getActivity());
    }
    return root;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    this.isVisibleToUser = isVisibleToUser;
    if (isVisibleToUser && getActivity()!=null) {
        isExecutedOnce =true;
        executeWithActivity(getActivity());
    }
}


private void executeWithActivity(Activity activity){
    //Do what you have to do when page is loaded with activity

}

在哪里调用这个函数?如果在Fragment的构造函数中调用它,它将返回null。

当onCreateView()方法被执行时,只需调用getActivity()。


那些仍然有问题的onAttach(活动活动),它只是改变了上下文-

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

在大多数情况下,保存上下文对您来说就足够了——例如,如果您想执行getResources(),您可以直接从上下文执行。如果你仍然需要将上下文放入你的活动中,那么就这样做吧

 @Override
public void onAttach(Context context) {
    super.onAttach(context);
    mActivity a; //Your activity class - will probably be a global var.
    if (context instanceof mActivity){
        a=(mActivity) context;
    }
}

由user1868713建议。


The other answers that suggest keeping a reference to the activity in onAttach are just suggesting a bandaid to the real problem. When getActivity returns null it means that the Fragment is not attached to the Activity. Most commonly this happens when the Activity has gone away due to rotation or the Activity being finished but the Fragment still has some kind of callback listener registered preventing it from being garbage collected. When the listener gets called if you need to do something with the Activity but the Activity is gone there isn't much you can do. In your code you should just check getActivity() != null and if it's not there then don't do anything. If you keep a reference to the Activity that is gone you are preventing the Activity from being garbage collected. Any UI things you might try to do won't be seen by the user. I can imagine some situations where in the callback listener you want to have a Context for something non-UI related, in those cases it probably makes more sense to get the Application context. Note that the only reason that the onAttach trick isn't a big memory leak is because normally after the callback listener executes it won't be needed anymore and can be garbage collected along with the Fragment, all its View's and the Activity context. If you setRetainInstance(true) there is a bigger chance of a memory leak because the Activity field will also be retained but after rotation that could be the previous Activity not the current one.


我正在使用OkHttp,我刚刚遇到了这个问题。


@thucnguyen的第一部分是正确的。

这发生在您在另一个线程中调用getActivity()时,该线程在片段被删除后结束。典型的情况是在HTTP请求完成时调用getActivity()(例如Toast)(例如onResponse)。

一些HTTP调用甚至在活动关闭后仍在执行(因为完成HTTP请求可能需要一段时间)。然后,我通过HttpCallback试图更新一些片段字段,并在尝试getActivity()时得到一个空异常。

http.newCall(request).enqueue(new Callback(...
  onResponse(Call call, Response response) {
    ...
    getActivity().runOnUiThread(...) // <-- getActivity() was null when it had been destroyed already

IMO的解决方案是防止当片段不再活跃时发生回调(不仅仅是Okhttp)。

解决办法:预防。

如果你看一下片段的生命周期(更多信息在这里),你会注意到有onAttach(Context Context)和onDetach()方法。它们分别在Fragment属于一个活动之后和停止之前被调用。

这意味着我们可以通过在onDetach方法中控制它来防止回调的发生。

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

    // Initialize HTTP we're going to use later.
    http = new OkHttpClient.Builder().build();
}

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

    // We don't want to receive any more information about the current HTTP calls after this point.
    // With Okhttp we can simply cancel the on-going ones (credits to https://github.com/square/okhttp/issues/2205#issuecomment-169363942).
    for (Call call : http.dispatcher().queuedCalls()) {
        call.cancel();
    }
    for (Call call : http.dispatcher().runningCalls()) {
        call.cancel();
    }
}

另一个好的解决方案是使用Android的LiveData和MVVM架构。 你可以在你的ViewModel中定义一个LiveData对象,并在你的片段中观察它,当LiveData值发生变化时,只有当你的片段处于活动状态时,它才会通知你的观察者(在这种情况下是片段),所以这将保证你的UI工作,只有当你的片段处于活动状态时才会访问活动。这是LiveData的一个优势

当然,当这个问题第一次被提出时,还没有LiveData。我把这个答案留在这里,因为在我看来,这个问题仍然存在,它可能会对某些人有所帮助。


在onActivityCreated()中调用getActivity()方法


我用这种方法解决了我的问题。我已经从前一个类传递了getApplicationContext,它已经访问了getApplicationContext。我已经将Inputstream对象传递给我的新类营养素。

try{
                    InputStream is= getApplicationContext().getAssets().open("nutrient_list.json");
                    Nutrients nutrients=Nutrients.getNutrients(topRecognition,is);

                  } catch (IOException e) {
                    e.printStackTrace();
                  }

编写一个通用方法,确保永远不会得到空Activity。

public class BaseFragment extends Fragment {
    private Context contextNullSafe;

     @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
         /*View creation related to this fragment is finished here. So in case if contextNullSafe is null
         * then we can populate it here.In some discussion in - https://stackoverflow.com/questions/6215239/getactivity-returns-null-in-fragment-function
         * and https://stackoverflow.com/questions/47987649/why-getcontext-in-fragment-sometimes-returns-null,
         * there are some recommendations to call getContext() or getActivity() after onCreateView() and
         * onViewCreated() is called after the onCreateView() call every time */
        if (contextNullSafe == null) getContextNullSafety();
    }


   @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        contextNullSafe = context;
    }

    /**CALL THIS IF YOU NEED CONTEXT*/
    public Context getContextNullSafety() {
                if (getContext() != null) return getContext();
                if (getActivity() != null) return getActivity();
                if (contextNullSafe != null) return contextNullSafe;
                if (getView() != null && getView().getContext() != null) return getView().getContext();
                if (requireContext() != null) return requireContext();
                if (requireActivity() != null) return requireActivity();
                if (requireView() != null && requireView().getContext() != null)
                    return requireView().getContext();
                
                return null;
            
        }

    /**CALL THIS IF YOU NEED ACTIVITY*/
    public FragmentActivity getActivityNullSafety() {
        if (getContextNullSafety() != null && getContextNullSafety() instanceof FragmentActivity) {
            /*It is observed that if context it not null then it will be
             * the related host/container activity always*/
            return (FragmentActivity) getContextNullSafety();
        }
        return null;
    }