Issue
I'm using WebView with javascript interface and sometimes when I call loadUrl
on the webView, mWebView.getContext()
return null
.
- How can a view have no Context ? Why ?
- Is a view whitout context still used or reusable ?
- What should I do when my view did not have a context ?
- Most important, if the view has no context, will
mWebView.post(new Runnable() { ...
be executed ? Is this code relevant ?
if (Looper.getMainLooper().getThread() == Thread.currentThread()) { mWebView.loadUrl("javascript:..."); } else { mWebView.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:..."); } }); }
Solution
2 common reasons of a null context to a view:
You're trying to get the context in the callback of an asynchronous (handler, network call) call but the activity/fragment is gone because of another action of the user (ex: pressed back). Therefore the view is detached and has no context anymore.
You have a memory leak somewhere and two or more instances of your activity and view hierarchy. Then something happen in the instance you're not refering to anymore but the view has lost the link to its context.
Regarding the handler. I am not sure if the view has its own handler or if it uses the handler of the Activity it is attached to, you'd probably have to read the source to find out. However the question is not really relevant: if the view has no context, you have a bigger problem: it's not on the screen.
Regarding whether the code in 5. is relevant, you would need to answer that questions: Why don't you know on which thread your code is running?
When you know on which thread you are, and if it makes sense to you not to be on the main thread, then using a handler is a valid way to execute your code on the main. As well as Activity.runOnUiThread()
Just remember that a Handler's lifecycle is not tied to the activity. So you should clear the queue of messages and runnables when your activity/fragment pauses
Answered By - znat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.