Note that there are some explanatory texts on larger screens.

plurals
  1. POHow should I refactor my code in order to avoid the Network on Main Thread exception on Android?
    primarykey
    data
    text
    <p>In my MainActivity I have a class initialization like so:</p> <pre><code>Presentation presentation = new Presentation("link"); </code></pre> <p>Presentation is a class which gets initialized using values from a .JSON file on a web server:</p> <pre><code>public Presentation(String URL) { // Do stuff doNetworking(); } private doNetworking() { // Network access here // This throws the Network on Main Thread exception } </code></pre> <p>In my MainActivity, I need all the values of Presentation to be there in the next step:</p> <pre><code>Presentation presentation = new Presentation(); // Do some stuff with it </code></pre> <p>Using the AsyncTask I am not sure how I should go about doing this, so far I have something like this: public Presentation(String URL) { // Do stuff new InitializePresentation().execute(URL); }</p> <pre><code>private class InitializePresentation extends AsyncTask&lt;String, Void, Boolean&gt; { // Amongst other things protected Boolean doInBackground(String... params) { // Do the networking stuff here } } </code></pre> <p>What I need is to refactor this code so that it is asynchroneous but behaves like a synchroneous call. Any help is greatly appreciated.</p> <p><em>edit</em> How does one refactor a code to accomplish this?</p> <pre><code>Bitmap b = new Bitmap(); Load bitmap from network; Use bitmap in imageview; </code></pre> <p>Can this be used in this fashion? Or do I have to use it like</p> <pre><code>Async, doInBackground() { Load bitmap from network Use bitmap in imageview Continue with application } </code></pre> <p>Thank you!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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