Created
May 16, 2018 16:39
-
-
Save anitaa1990/4096a57928c1d5fb6c66db984c48b6f3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AsyncTaskReferenceLeakActivity extends AppCompatActivity { | |
private TextView textView; | |
private BackgroundTask backgroundTask; | |
@Override | |
protected void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_first); | |
/* | |
* Executing AsyncTask here! | |
* */ | |
backgroundTask = new BackgroundTask(textView); | |
backgroundTask.execute(); | |
} | |
/* | |
* Fix number 1 | |
* */ | |
private static class BackgroundTask extends AsyncTask<Void, Void, String> { | |
private final WeakReference<TextView> messageViewReference; | |
private BackgroundTask(TextView textView) { | |
this.messageViewReference = new WeakReference<>(textView); | |
} | |
@Override | |
protected String doInBackground(Void... voids) { | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
return "The task is completed!"; | |
} | |
@Override | |
protected void onPostExecute(String s) { | |
super.onPostExecute(s); | |
/* | |
* Fix number 3 | |
* */ | |
TextView textView = messageViewReference.get(); | |
if(textView != null) { | |
textView.setText(s); | |
} | |
} | |
} | |
@Override | |
protected void onDestroy() { | |
super.onDestroy(); | |
/* | |
* Fix number 2 | |
* */ | |
if(backgroundTask != null) { | |
backgroundTask.cancel(true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment