0

In my application I use getPreferences(Context.MODE_PRIVATE) to get the preferences that the use has set. Note that I'm using getPreferences and not getSharedPreferences in my whole project.

Now I want to get the preferences from a BroadcastReceiver but here is the problem: It can only use the method getSharedPreferences. I think with this I get an other preference file right? So how can I get my 'normal' preferences (which I can get with the getPreferences method) with the getSharedPreferences method?

2 Answers 2

1

The getPreferences() method should only be used inside an Activity and it is not possible to use it inside a BroadcastReceiver. Instead, You have to use getSharedPreferences(String prefKey, int mode) to get Preferences on all app components. Look here under "Saving Persistent State":

http://developer.android.com/reference/android/app/Activity.html

2
  • So both methods give me the same preference file? I thought that these are two different files and I can not access them from each other. So all settings I write are accessable with getPreferences and getSharedPreferences also if I use an editor created from getPreferences to write them?
    – Cilenco
    Jun 12, 2014 at 10:54
  • 1
    Don´t punk me if I am not right, but I think yes if You are using the activity´s class name. getPreferences() is passing the activity's class name as the preferences name. So maybe it would work if You use this parameter in getSharedPreferences() Jun 12, 2014 at 11:00
1

getPreferences In this call you do not pass the name for your preferences, that does not mean that this preferences object is created without a name. Its simply that this call assigns a default name to the preference file created this way.

And you always need a reference to a activity to make a call to this method. ACTIVITY.this.getPreferences(mode)

getSharedPreferences In this case you create a preferences file by assigning a name to it.

getSharedPreferences(name, mode)

The solution

  1. Either use getSharedPreferences(name,mode) throughout in your app

  2. or try to get what name getPreferences(mode) assigns to the sharedPreference file. And then in your receiver use that name with getSharedPreferences(name,mode).

  3. Pass a reference of a visible activity to the receiver. (This may be prone to some issues)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.