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.. !!!
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;
}
}
Both Solution will work that i am posting. Try any of them.
Solution 1 :
Try to call your AsynTask
in onActivityCreated
rather then in onCreateView
as 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
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
.
It may be possible that async task is going on but fragment closed so u have pass getActivty() to AsyncTask.