Pol
Pol

Reputation: 181

WeakReference.get() returns null after being checked for it

I have an async task executed from a view and in its onPostExecute I retrieve an instance of the view using weakReference.get() and I check that this instance is different from null. Later in the onPostExecute I call a method from weakReference.get() and I get a NullPointerException.

  1. Would it be solved by calling it from the reference I got?

  2. Is there any way in which the weakReference.get() value will differ from the reference I got at the start?

For example is it possible that the method() call of the view will lead to a NullPointerException?

Sample :

private WeakReference<View> weakReference;

[...]

@Override
protected void onPostExecute(Boolean result) {    
    View v = weakReference.get();
    if (v == null) {
        return;
    }
    […]
    getView().method();
}

Thank you very much.

Upvotes: 1

Views: 2376

Answers (2)

Vito
Vito

Reputation: 1434

I don't think that saving View's references during AsyncTask it's good approach. You should change your architecture of doing async work in different way. Please have a look on Android Jetpack, there you can find best practices approaches for almost every case in Android development. And any problems related to "activity destroyed" state will be handled automatically if you will use Android Architecture Components.

Regarding your case WeakReference can be cleared in any time, when Garbage Collector decides. So it's normal situation that you can see "null" at any moment.

"Is there any way in which the weakReference.get() value will differ from the reference I got at the start?" - Yes, for example user will rotate screen or android system can destroy and recreate your activity when memory amount is low. After that Activity with all views will be recreated and this means system will create new instances of all views.

"is it possible that the method() call of the view will lead to a nullPointerException?" - Yes, it's actually can happens very often. For example, you started AsyncTask and after that before finish of AsyncTask - rotate your screen.

Upvotes: 2

Jeel Vankhede
Jeel Vankhede

Reputation: 12118

Q1: Would it be solved by calling it from the reference I got?

Yes, it'll be solved by calling it from reference. So that, if reference is null, handle it or else use it as method() calling.


Q2: Is there any way in which the weakReference.get() value will differ from the reference I got at the start?

Yes, if there's any configuration changes happens (activity/fragment recreates itself), means that view is recreated and your old view reference would be null.


Conclusion: It's good practice to have reference of your view and perform any operation from that reference further

Upvotes: 1

Related Questions