I have an IntentService which updates a preference like this:
SharedPreferences.Editor editor = userPrefs.edit();
editor.putInt("COUNT", intCount);
editor.commit();
In my main activity I am listening for preference changes and update a TextView
userPrefsListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("COUNT")) {
final TextView txvCounter = (TextView) findViewById(R.id.TXV_COUNTER);
if(txvCounter != null) {
SharedPreferences userPrefs = getSharedPreferences("USER_SCORE", 0);
int intCount = userPrefs.getInt("COUNT", 0);
txvFishcounter.setText(String.format("%03d",intCount));
}
}
}
};
userPrefs.registerOnSharedPreferenceChangeListener(userPrefsListener);
For Android 2.3 everything works fine, but for 2.2 I’m getting CalledFromWrongThreadException everytime the OnSharedListener is triggered.
Thanks for your Help!
The reason why the
CalledFromWrongThreadExceptionis raised, is because theOnChangeListeneris not supposed to be called from theIntentService.What you could do though, is sending a Broadcast (where you can actually include the value as well).
In case you are only using the
SharedPreferencefor communication, you can replace it entirely (and I would recommend this, as SharedPreferences are wasting Write Cycles).You could use a code like this for sending a Broadcast:
You should include a custom permission as well, so other apps don’t get the Broadcast, but it is not necessarily needed.
To receive the Broadcast, register a Receiver in your Activity, eg
Also you should consider using
Handlers, so your methods in the OnChangeListener call are run by the MainUI thread.Example:
This has also the advantage of running the code delayed with
runDelayed(), so you don’t have to usesleep, and you UI will be still responding.