Reputation: 4007
Im using an AsyncTask called GetSalesTask as an inner class in my Activity, but it seems that it is leaking, I can see a lot of instances alive from the same GetSalesTask class, in other words it seems that the instances of GetSalesTask are alive and are not cleaned from memory. Can you please point out where can my problem be?
class LeekClass extends BaseProfileActivity{
void callTask()
{
new GetSaleTask().execute();
}
private class GetSalesTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
showList(true);
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void... params) {
List<Sale> saleList = get Data From Database
mItems.clear();
mItems.addAll(saleList);
if (saleList.size() > 0)
return true;
else
return false;
return false;
}
@Override
protected void onPostExecute(Boolean result) {
BaseProfileActivity baseAct = (BaseProfileActivity) getActivity();
if (baseAct != null && getView() != null && mAdapter != null) {
mAdapter.notifyDataSetChanged();
showList(true);
baseAct.getProgress().setVisibility(View.GONE);
}
}
}
}
The methods showList(true); getView(); and the variables mItems,mAdapter are defined in the activity.
Upvotes: 1
Views: 2701
Reputation: 5651
Consider setting the task to null in onPostExecute and checking for null before starting the task. The GC should in theory trace back to the null and determine everything is ok to clean up.
if (myTask==null) {
myTask = new getSaleTask();
myTask.execute();
}
somewhere in onPostExecute();
myTask =null;
I've switched to doing the above and passing WeakReference<T>
Pass a WeakReference to the class. This is easier for me to do in a constructor. Below I pass a WeakReference<Context>
to the class. Save the weakReference in the constructor of the class.
new getSaleTask(new WeakReference<Context>(getApplicationContext());
public getSaleTask(WeakReference<Context> weakReference){
this.weakReference = weakReference;
}
then in the class you get the WeakReference as follows.
Context context = weakReference.get();
For whatever reason set the weakReference to null when the task is finished.
Upvotes: 1