Search code examples
androidandroid-studiodependency-injectionguiceroboguice

RoboGuice inject different SharedPreferences


In RoboGuice when I'm using:

@Inject
SharedPreferences prefs;

It injects the default SharedPreferences
How do I inject not default preferences?
like context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE)


Solution

  • 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

    bindConstant()
        .annotatedWith(SharedPreferencesName.class)
        .to("com.mypackage.myapp_preferences");  
    

    Example

    public class MyActivity extends RoboActivity {
      @Inject SharedPreferences sharedPreferences;
    } 
    

    Provider Example

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

    From: https://github.com/roboguice/roboguice/wiki/Provided-Injections

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

    @Inject
    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