Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6167487
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T22:31:18+00:00 2026-05-23T22:31:18+00:00

I am loading some JSON data in an AsyncTask, as I want to show

  • 0

I am loading some JSON data in an AsyncTask, as I want to show the download progress in the UI. The download is working fine and the publishProgress method gets called regularly (every 100 JSON objects), but onProgressUpdate and onPostExecute do not get actually executed, until all background operations are done (i.e. all calculations which require the doInBackground result).

Log looks roughly like this:

AsyncTaskCaller.downloadWithAsyncTask: executing AsyncTask

MyAsyncTask.onPreExecute: AsyncTask started

MyAsyncTask.doInBackground: Download 0%
MyAsyncTask.doInBackground: Download 10%
...
MyAsyncTask.doInBackground: Download 90%
MyAsyncTask.doInBackground: Download 100%

AsyncTaskCaller.processResult: Results processed

// all background calculations finished

MyAsyncTask.onProgressUpdate: Download 0%
MyAsyncTask.onProgressUpdate: Download 10%
...
MyAsyncTask.onProgressUpdate: Download 90%
MyAsyncTask.onProgressUpdate: Download 100%

MyAsyncTask.onPostExecute: AsyncTask ended

MyActivity.updateUiAfterDownload

This is how my code is calling the data:

MyActivity:

final Runnable mSynchroniseContacts = new Runnable() {
    public void run() {
        /** get oAuth tokens for synchronisation */
        MyApp app = (MyApp) getApplication();
        OpenAuthTokens myTokens = app.getAccessTokens();

        // mockup code to load contacts
        MyContact[] contacts = AsyncTaskCaller.loadContacts(myTokens, MyActivity.this);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.synchronisation_activity);

    statusText = (TextView) findViewById(R.id.synchronisation_status_text);

    mSynchroniseContacts.run();
}

AsyncTaskCaller:

private static JSONArray records = null;

public static MyContact[] loadContacts(OpenAuthTokens myTokens, Context context) {
    MyAsyncTask contactDownloader = new MyAsyncTask(context, myTokens) {
        @Override
        protected void onPostExecute(JSONArray result) {
            super.onPostExecute(result);

            records = result; // assigning result to static class variable, to avoid calling contactDownloader.get(), which apparently blocks the UI thread according to http://stackoverflow.com/questions/5583137/asynctask-block-ui-threat-and-show-progressbar-with-delay
        }
    };

    contactDownloader.execute(url);

    // wait until contacts are downloaded
    while(!SforceContactDownloadTask2.isFinished()) {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            Log.e(TAG, e.getCause() + " - " + e.getMessage());
            e.printStackTrace();
        }
    }   

    // some code to convert JSONArray records into MyContact[] myContacts

    return myContacts;
}

MyAsyncTask (code to log as above was not explicitly pasted):

@Override
protected void onPreExecute() {
    finished = false;
}

@Override
protected void onPreExecute() {
    finished = false;
}

@Override
protected JSONArray doInBackground(String... url) {

    StringBuffer dataString = new StringBuffer();

    try {

        boolean isOnline = ConnectivtiyChecker.isInternetAvailable(context);

        if (isOnline) {

            /** send as http get request */
            URL urlObject = new URL(url[0]);
            HttpURLConnection conn = (HttpURLConnection) urlObject.openConnection();
            conn.addRequestProperty("Authorization", "OAuth " + myTokens.get_access_token());

            /** prepare response reader */
            JSONArray records = null;
            byte data[] = new byte[MAX_BUFFER_SIZE];
            int currentByteReadCount = 0;
            InputStream stream = null;
            BufferedInputStream input = null;

            try {
                /** get response input stream */
                stream = conn.getInputStream();
                input = new BufferedInputStream(stream);

                /** read response from input stream */
                while ((currentByteReadCount = input.read(data)) != -1) {
                    String readData = new String(data, 0, currentByteReadCount);
                    dataString.append(readData);

                    //code to figure progress out

                    // publishing the progress (every 5%)...
                    if (progress % (total / 20) == 0 ) {
                        publishProgress((int)(progress * 100 / total));
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getCause() + " - " + e.getMessage());
                e.printStackTrace();
            } finally {
                // close streams
                if (input != null) {
                    input.close();
                }
                if (stream != null) {
                    stream.close();                     
                }
            }

            /** transform response into JSONArray */
            String result = dataString.toString();
            JSONObject object = (JSONObject) new JSONTokener(result).nextValue();
            records = object.getJSONArray("records");

            return records;
        } else {
            return null;
        }
    } catch (Exception e) {
        Log.e(TAG, e.getCause() + " - " + e.getMessage());
        e.printStackTrace();
        return null;
    }
}

@Override
protected void onProgressUpdate(Integer... changed) {
    Log.d(TAG, "Download " + changed[0] + "%");
}

@Override
protected void onPostExecute(JSONArray result) {
    finished = true;
}

public static boolean isFinished() {
    return finished;
}

Any ideas how to de-block the UI?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T22:31:19+00:00Added an answer on May 23, 2026 at 10:31 pm

    You appear to be calling Thread.sleep() on the main application thread. Do not do this. Please write your application to be properly asynchronous.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying this source where jqGrid gets some json data from django: link Unfortunately
Summary of the issue: When I am loading some data into my iPhone application
I'm using some client-side JavaScript code to pull a lot of JSON data from
I'm loading some json through apache as per: http://arguments.callee.info/2010/04/20/running-apache-and-node-js-together/ The JSON however is outdated
I have a UITableView which is populated with some parsed JSON twitter data. The
I'm trying to download some data using pure javascript/html from cross-domain, dropbox to be
I'm using a jquery datatable which is loading some JSON dynamically using the sAjaxSource
I am trying to change the accessor in a cell during some data loading
So I am loading some Json that is transformed from RSS beforehand. This RSS
I'm loading some HTML via Ajax with this format: <div id=div1> ... some content

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.