Created
May 16, 2018 16:17
-
-
Save anitaa1990/9c85bebbd9020fcd20666767b69d9039 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 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"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 39 is setting text on a non-main thread, it will crash.