Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to load and process HTML from Ajax request
    text
    copied!<p>I'd like to run a background task in my android app which sends an Ajax request, parses/manipulates the HTML from the response and creates a new object from the HTML data.</p> <p>It is very easy to request and manipulate the data and create new object (without multithreading). I can create a WebView, load a local HTML file with some JavaScript functions, send an Ajax request from the JavaScript, manipulate it with jQuery and send it back via 'MyJavaScriptInterface'.</p> <h2>Java Code Snippet</h2> <pre><code>// method of 'MyJavaScriptInterface' public void processJSON(String jsonArrayString) { try { JSONArray array = new JSONArray(jsonArrayString); for (int i = 0; i &lt; array.length(); i++) { JSONObject row = array.getJSONObject(i); // MyObject obj = new MyObject(row.getString("title"), // row.getString("href") ); // do something fancy with the object } } catch (JSONException e) { Log.e("MyJavaScriptInterface", e.getMessage(), e); } } // initialize WebView webView.addJavascriptInterface(new MyJavaScriptInterface(), "android"); // load local html file with JavaScript functions webView.loadUrl("file:///android_asset/www/index.html"); </code></pre> <h2>JavaScript Code Snippet</h2> <pre><code>$.ajax({ url: 'http://example.com/index', success: function(data) { $(data).find('#container').children().each(function(){ jsonArray.push( { 'title': this.title, 'href': this.href } ) }); jsonArray = JSON.stringify(jsonArray); // send 'jsonArray' back to the android device android.processJSON( jsonArray ); } }); </code></pre> <h2>HTML Code Snippet:</h2> <p>This is what the website looks like - but I have no control over the content.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;!-- header --&gt; [...] &lt;body&gt; &lt;div id="container"&gt; &lt;a href="someUrl" title="someTitle"&gt;&lt;img src="relativeImageUrl"&gt;&lt;/a&gt; &lt;!-- more links --&gt; [...] &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I'd like to load the data in a separate thread but this is not possible with a WebView, so here are my questions:</p> <h1>Questions</h1> <ul> <li>How should I perform the same task <strong>without</strong> jQuery and JavaScript?</li> <li>Is there an easy way to access the DOM in Java (or do i have to parse the whole XML structure of the HTML data)?</li> </ul> <p>Thanks in advance!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload