Fragment getActivity is always returning null from

2019-09-18 06:42发布

I have called an AsyncTask inside my fragment. I was calling getActivity() from within doInBackground of that AsyncTask, but getActivity is returning null.

If I call getActivity outside from AsyncTask its working properly, but I need instance of activity inside my asyncTask itself.

Any help would be appreciated.. !!!

4条回答
干净又极端
2楼-- · 2019-09-18 07:14

Both Solution will work that i am posting. Try any of them.

Solution 1 :

Try to call your AsynTask in onActivityCreated rather then in onCreateViewas sometimes it happens Activity instance return to be null in onCreateView.

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
 // call AsynTask here, getActivity() not return null here
}

Solution 2 :

Get activity instance when fragment is attached on Activity and then use Activity context in your AsynTask(No need to call getActivity()).

private Activity mContext;

// called for API equal or above 23
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.mContext = (Activity) context;
}

/*
* Deprecated on API 23
*/
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.mContext = activity;
}

// Use mContext in asyntask 
查看更多
劳资没心,怎么记你
3楼-- · 2019-09-18 07:25

In your fragment add

Activity mActivity; //declare as global variable

@Override
public void onAttach(Context context) {
super.onAttach(context);
  if (context instanceof Activity){
    mActivity=(Activity) context;
}
}

then use mActivity instead of getActivity() in your AsyncTask.

查看更多
戒情不戒烟
4楼-- · 2019-09-18 07:26

Pass Activity to AsyncTask method

new Demo().execute(getActivity());

public class Demo extends AsyncTask<Activity,Void,Void>{
    Activity activity=null;
    @Override
    protected Void doInBackground(Activity... params) {
        activity=params[0]; //get the activity instance 
        //Do your task

        return null;
    }
}
查看更多
混吃等死
5楼-- · 2019-09-18 07:37

It may be possible that async task is going on but fragment closed so u have pass getActivty() to AsyncTask.

查看更多
登录 后发表回答