Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save anitaa1990/9c85bebbd9020fcd20666767b69d9039 to your computer and use it in GitHub Desktop.
Save anitaa1990/9c85bebbd9020fcd20666767b69d9039 to your computer and use it in GitHub Desktop.
public class AnonymousClassReferenceLeakActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
textView = findViewById(R.id.activity_text);
textView.setText(getString(R.string.text_inner_class_1));
findViewById(R.id.activity_dialog_btn).setVisibility(View.INVISIBLE);
/*
* Runnable class is defined here
* */
new Thread(new LeakyRunnable(textView)).start();
}
private static class LeakyRunnable implements Runnable {
private final WeakReference<TextView> messageViewReference;
private LeakyRunnable(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
TextView textView = messageViewReference.get();
if(textView != null) {
textView.setText("Runnable class has completed its work");
}
}
}
}
@zmer007
Copy link

zmer007 commented Jul 19, 2019

Line 39 is setting text on a non-main thread, it will crash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment