Search code examples
androiduser-interfaceactionbarsherlock

Android - onOptionsItemSelected UI freeze until complete


This problem is very simple to describe, but I didn't find an answer.

I'm using ActionBarSherlock (if relevant), and I have a menu option to refresh the contents of a fragment. It all works fine.

the problem I have is that when I press the refresh button, it will freeze the UI until the process finishes, and I want to show dialogs and other stuff.

Here's the piece of code:

"public class MainActivity extends SherlockFragmentActivity" method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.action_refresh:
        Thread.sleep(10000); // removed try/catch code for practical purposes.
      break;
    }
    return true;
}

In this case, the UI freezes for 10 seconds (and the refresh button stays as "selected").

I don't think it is related to my app code but to an ABS or android thing.

Just a fact: I use threads and asynctasks inside this method, so that's not the problem.

Any thoughts on how to make UI updateable (or run this method like if a Thread)?


Solution

  • You are calling Thread.sleep(10000); on the UI thread so it will freeze. You should never do this.

    Just a fact: I use threads and asynctasks inside this method, so that's not the problem.

    I'm not sure what you mean by "that's not the problem" but you can move Thread.sleep(...) to one of your Threads or AsyncTask that you have

    Any thoughts on how to make UI updateable (or run this method like if a Thread)?

    You say you are using AsyncTask in this method. Update the UI in your onPostExecute() after your code has run (or any other method you wish in AsyncTask besides doInBackground()