Last active
January 11, 2020 13:35
-
-
Save shikto1/7dc937b098930cc34140668596e3794e to your computer and use it in GitHub Desktop.
This file contains 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 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