I am making an Android mobile app. I have a WeakReference to my Activity in the AsyncTask to ensure that it can be garbage collected.
When onPostExecute()
g
I think it's NOT safe. I get a NPE at activity.msgWebView.setVisibility(View.GONE);
inside Handler.
```java
private static class HttpStatusHandler extends Handler {
private WeakReference<MessageWebViewActivity> activityWeakReference;
public HttpStatusHandler(WeakReference<MessageWebViewActivity> activityWeakReference) {
this.activityWeakReference = activityWeakReference;
}
@Override
public void handleMessage(Message msg) {
MessageWebViewActivity activity = activityWeakReference.get();
if (activity != null) {
if (msg.what == MSG_URL_OK) {
activity.loadUrl(activity.url);
} else if (msg.what == MSG_URL_ERROR) {
activity.msgWebView.setVisibility(View.GONE);
activity.clPageError.setVisibility(View.VISIBLE);
activity.progressbarLayout.setVisibility(View.GONE);
}
}
}
}
```
It's safe!
As soon as you assign the result of get() to a variable, you have a strong reference again which blocks gargbage collection for this object as long as the new reference exists.
Of course, after this assignment you need to check if activity is null.