I need to parse JSON content out of every page in my WebView, before it is shown to the user.
In order to do so, I need to parse the JSON element and only then I’m able to use the shouldOverrideUrlLoading
method. I can’t use it before I’ve parsed the JSON object because I rely on that element as part of my implementation of that method.
I have created a variable called jsonParsed
to indicate whether I have all needed information out of the JSON object.
At first, it is initialized to be false.
When I get a response from the server I know the object was parsed so I change the variable to be true in the onLoaded
method, and then the code is ready to get the information and check it.
This is the wanted process:
- Opening new page by the user
- Entering automatically to
shouldOverrideUrlLoading
and then to theif
statement(JSON wasn't parsed yet) - Getting the JSON response in
OnResponse
- Going back to
shouldOverrideUrlLoading
and entering theelse
statement (JSON is parsed)
As you can see, each process should go through both if
and else
statements, the if
before the JSON was parsed, and the else
after it was parsed.
The problem:
shouldOverrideUrlLoading
is reached every step 1, but each time it goes into a different statement. The first time goes into the if
(steps 2+3), and the next one goes into the else
(step 4) and this process repeats itself...
I think the this line webView.loadUrl(loadingURL);
doesn't call shouldOverrideUrlLoading
for some reason.
Here is my code snippet:
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
mProgressDialog.show();
}
@Override
public boolean shouldOverrideUrlLoading(WebView wView, String url){
loadingURL=url;
if (!jsonParsed){
/** JSON object is not parsed
* Some code for adding request
to requestQueue and than loading new url in onResponse method... */
}
else {
/** JSON object is parsed, starting checking process
* I need to check this URL and decide whether or not to override it*/
jsonParsed=false;
Root root = new Gson().fromJson(jsonResponse, Root.class);
for (Page page : root.query.pages.values()) {
firstParagraph=page.extract; //Parsing process, works fine
}
if (firstParagraph!=null) {
//If the webView isn't Wikipedia's article, it will be null
if (firstParagraph.contains(allowedContent)) {
//Passing URL to view
return true;
}
}
return false; //The URL leads to unallowed content
}
}
@Override
public void onPageFinished(WebView view, String url) {
CloseBlocksAndDisableEdit(view);
mProgressDialog.dismiss();
}
private final Response.Listener<String> onLoaded = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
jsonResponse=response; //Getting response
jsonParsed=true; //Object was examined
webView.loadUrl(loadingURL);
}
};
What can be the cause of this problem?
If it's not possible in this way, I'd like to know which way is better...