Fragment getActivity is always returning null from Async Task

谁说胖子不能爱 提交于 2019-12-13 07:41:41

问题


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.. !!!


回答1:


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;
    }
}



回答2:


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:


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:


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



来源:https://stackoverflow.com/questions/42850194/fragment-getactivity-is-always-returning-null-from-async-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!