Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a basic example for requesting data from a webserver using the AsyncTask from an Android application.</p> <p>First define the async class. Note that the constructor takes a listener which we use to publish the result once ready.</p> <pre><code>public class Webservice extends AsyncTask&lt;String, Void, String&gt; { private DialogListener dialogListener; public Webservice(final DialogListener dialogListener) { this.dialogListener = dialogListener; } @Override protected String doInBackground(final String... strings) { // We cant trigger onComplete here as we are not on the GUI thread! return ""; } protected void onPostExecute(final String result) { dialogListener.onComplete(result); } } </code></pre> <p>Basic server class for handling various network communications:</p> <pre><code>public class Server { public void queryServer(final String url, final DialogListener service) { // Simulate slow network... try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } new Webservice(service).execute(url); } } </code></pre> <p>We can now use this code inside our activity without having to worry how long the call takes as it is not going to halt the GUI as it is executed async.</p> <pre><code>Server s = new Server(); // Async server call. s.queryServer("http://onto.dk/actions/searchEvents.jsp?minLatE6=55640596&amp;minLngE6=12078516&amp;maxLatE6=55642654&amp;maxLngE6=12081948", new DialogListener() { @Override public void onComplete(final String result) { toast("complete"); } @Override public void onError() { toast("error"); } }); </code></pre>
 

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