I just read this post on how to avoid memory leaks with AsyncTask. The post proposed using a WeakReference and supplying a TextView as the object of the WeakReference.
In my code, I need to supply multiple parameters to the AsyncTask (not just one as shown in the post). So what I did was create an inner class with the parameters needed in the AsyncTask and use the said class as the object of the WeakReference.
private static class AddBooksToDatabase extends AsyncTask<String, String, String> {
private final WeakReference<AddBooksDbParams> mReference;
private String TAG = "TownFragment";
Context mContext;
WaveLoadingView waveView;
TextView infoText;
String townName;
File mFile;
public AddBooksToDatabase(AddBooksDbParams params) {
this.mReference = new WeakReference< >(params);
mContext = mReference.get().mContext;
infoText = mReference.get().infoText;
townName = mReference.get().townName;
mFile = mReference.get().mFile;
waveView = mReference.get().waveView;
}
@Override
protected String doInBackground(String... strings) {
TownHelper helper = TownHelper.getInstance(mContext, dbName);
SQLiteDatabase database = helper.getWritableDatabase();
int booksSize = getFilesInFolder(mFile).size();
//Stuffs
return null;
}
@Override
protected void onPreExecute() {
if (waveView != null) {
waveView.setVisibility(View.VISIBLE);
}
}
@Override
protected void onPostExecute(String s) {
if (waveView != null) {
waveView.setVisibility(View.GONE);
}
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d(TAG, "Progress report = " + values[0]);
infoText.setText(values[0]);
}
@Override
protected void onCancelled() {
cancel(true);
}
}
//Parameters for AddBooksToDatabase. This is to enable holding of a
//single object of this class in WeakReference
private class AddBooksDbParams {
Context mContext;
WaveLoadingView waveView;
TextView infoText;
String townName;
File mFile;
AddBooksDbParams(TextView infoText, Context context, File file,
String townName, WaveLoadingView waveView) {
this.infoText = infoText;
mContext = context;
mFile = file;
this.townName = townName;
this.waveView = waveView;
}
}
When I want to execute the AsyncTask:
AddTownsDbParams params = new AddTownsDbParams(infoText, getActivity(), folder, mShelfLabel, mWave);
addBooksTask = new AddBooksToDatabase(params).execute();
The code is working quite aright but I want to know if I am doing wrong.
WeakReference<Context>
,WeakReference<WaveLoadingView>
,WeakReference<TextView>
,WeakReference<String>
,WeakReference<File>
? \$\endgroup\$