简体   繁体   中英

getActivity() returns null in AsyncTask when called from another class

I have an AsyncTask to perform a task.I call this from the same class where the AsyncTask is written and from another class.

I have this statement in the code snippet for fetching user's current location:

GPSTracker gps = new GPSTracker(getActivity());

When called from same class, getActivity() has value but when called from another class, getActivity() returns null.

I tried using passing the context through constructor also:

 Context mContext;
 AsyncDataUpdate(Context context){
             this.mContext = context;
              }
GPSTracker gps = new GPSTracker(mContext);

which isn't working either. What might be the reason? Any help will be greatly appreciated.

Use mContext variable after calling of AsyncDataUpdate class constructor as:

GPSTracker gp;
Context mContext;
private AsyncDataUpdate(Context context){
     this.mContext = context;
     this.gps = new GPSTracker(this.mContext);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM