NickF NickF - 4 months ago 41
Android Question

RoboGuice inject different SharedPreferences


when I'm using:

SharedPreferences prefs;

It injects the default

How do I inject not default preferences?

context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE)


From Roboguice documentation:

Shared Preferences

Class: SharedPreferences

Provider: SharedPreferencesProvider

Scope: Transient Injection

Points: Constructors, Fields, Methods By default

roboguice will retrieve an instance of Android SharedPreferences using the filename: "default". This is not the default file name android uses for your shared preferences. If you would like to override the file name then you can set up a binding when RoboGuice is initialized.

Android Default Shared Preferences File Name Binding



public class MyActivity extends RoboActivity {
  @Inject SharedPreferences sharedPreferences;

Provider Example

public class MyActivity extends RoboActivity {
  @Inject Provider<SharedPreferences> sharedPreferencesrProvider;


I haven't used RoboGuice before, but I'm pretty sure that:

SharedPreferences prefs;

means the same as:

SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);

so if you want to get a key value, you would use only:

int highScore = prefs.getInt("my_prefs", defaultValue);

and to put a new value:

editor.putInt("my_prefs", newHighScore);

Hope it will help