tags:

views:

101

answers:

1

I know how to use handlers to update UI elements such as progress bars toasts etc.

The problem I am having is when the context goes away such as the user pressing the back button or the Activity finishing for some reason. This causes my application to crash often.

I tried using getApplicationContext() (Thinking that this would be available throughout my entire application) but this did not work, ever - instead my application crashed!

I put try catch blocks around all UI update code, this works but is it necessary?

So...what is the bast way to handle this?

+3  A: 

The problem I am having is when the context goes away such as the user pressing the back button or the Activity finishing for some reason. This causes my application to crash often.

You will also get this, by default, if the user changes screen orientation, as the original activity is destroyed and a new one created.

I tried using getApplicationContext() (Thinking that this would be available throughout my entire application) but this did not work, ever - instead my application crashed!

The application context is useless from the standpoint of manipulating the UI.

So...what is the bast way to handle this?

In the end, what you need is for your thread to deliver an event to the right activity. Some techniques that people have used include:

  • Use a listener pattern (e.g., service manages the thread, activities register and unregister listeners with the service, thread invokes the listeners on key events)
  • Put the "current" instance of the activity in a static data member, which the thread uses to find out which one should be used (dangerous due to memory leaks and fails if you need multiple instances)
  • Limit background threads to ones that cache data, which the activity pulls (e.g., via polling) as needed
CommonsWare