Skip to content

Instantly share code, notes, and snippets.

@shikto1
Last active January 11, 2020 13:35
Show Gist options
  • Save shikto1/7dc937b098930cc34140668596e3794e to your computer and use it in GitHub Desktop.
Save shikto1/7dc937b098930cc34140668596e3794e to your computer and use it in GitHub Desktop.
public class GoodActivity extends Activity {
TextView textView;
AsyncTask task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async);
textView = (TextView) findViewById(R.id.textView);
task = new BackgroundTask(textView).execute();
}
@Override
protected void onDestroy() {
task.cancel(true);
super.onDestroy();
}
private static class BackgroundTask extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> textViewReference;
public BackgroundTask(TextView resultTextView) {
this.textViewReference = new WeakReference<>(resultTextView);
}
@Override
protected void onCancelled() {
// Cancel task. Code omitted.
}
@Override
protected String doInBackground(Void... params) {
// Do background work. Code omitted.
return "some string";
}
@Override
protected void onPostExecute(String result) {
TextView view = textViewReference.get();
if (view != null) {
view.setText(result);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment