1

Is it considered bad practice to read from SharedPreferences in a while loop? Is the data always read from internal/external storage, or is it cached in memory?

I'm doing this because one of the threads in my applications needs to know if a change has been made since the last iteration.

quietmint
  • 13,885
  • 6
  • 48
  • 73
Cethy
  • 551
  • 6
  • 18
  • I believe the access will go always to the IO. You can always test it with [StrictMode](http://developer.android.com/reference/android/os/StrictMode.html) and see if there is significant impact. – oxygenpt Oct 26 '13 at 14:53

2 Answers2

5

It may work but it's definitely bad practice to wait for an event using while-loop. To catch some event try to use Observer pattern. The idea of this pattern is to split up objects into observers(wait for an event) and observable(register/catch an event and notify observers)

There's built in class and interface in Java for this approach. Example:

Observable:

import java.util.Observable;

public class SharedPrefsWrapper extends Observable{

    public static final int EVENT_PUT_STRING = 0;

    public void putString(String key, String value){
        //put string into shared preferences
        //then notify Observers
        notifyObservers(EVENT_PUT_STRING);
    }
}

Observer:

import java.util.Observable;
import java.util.Observer;

public class SomeActivity extends Activity implements Observer {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.some_activity);

        SharedPrefsWrapper prefs;
        //...
        prefs.addObserver(this);
    }

    @Override
    public void update(Observable observable, Object event) {
        if(event.equals(SharedPrefsWrapper.EVENT_PUT_STRING)){
            //event of writing string is caught
        }
    }
}
eleven
  • 6,779
  • 2
  • 32
  • 52
3

A while loop is definitely not desirable here.

Instead, use registerOnSharedPreferenceChangeListener with a SharedPreferences.OnSharedPreferenceChangeListener to listen for changes. As mentioned in other answers, this works across threads within the same application (e.g., a service can listen for changes made by an activity) but not across different applications.

quietmint
  • 13,885
  • 6
  • 48
  • 73