Issue
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
.
Would it be solved by calling it from the reference I got?
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.
Solution
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
Answered By - Jeel Vankhede
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.