Skip to content Skip to sidebar Skip to footer

Fragment Getactivity Is Always Returning Null From Async Task

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 ou

Solution 1:

Pass Activity to AsyncTask method

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

publicclassDemoextendsAsyncTask<Activity,Void,Void>{
    Activity activity=null;
    @Override
    protected Void doInBackground(Activity... params) {
        activity=params[0]; //get the activity instance //Do your taskreturnnull;
    }
}

Solution 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 Activitycontext in your AsynTask(No need to call getActivity()).

privateActivity mContext;

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

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

// Use mContext in asyntask 

Solution 3:

In your fragment add

Activity mActivity; //declare as global variable@OverridepublicvoidonAttach(Context context) {
super.onAttach(context);
  if (context instanceofActivity){
    mActivity=(Activity) context;
}
}

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

Solution 4:

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

Post a Comment for "Fragment Getactivity Is Always Returning Null From Async Task"