GetPreferences (MODE_PRIVATE) - undefined in BroadcastReceiver

I have an application with activity and service, I need to save some value in activity and get in the service.

I could save the value using SharedPreferences in activity, however, when I try to get the value in BroadcastReceiver, it says getPreferences undefined for the service.

How can I get my value in BroadcastReceiver?

+4
source share
2 answers

EDITED to reflect the change in the original question from Service to BroadcastReceiver .

Instead of using getPreferences(int mode) in Activity use ...

 getSharedPreferences(String name, int mode). 

The getPreferences(int mode) method is a convenience method for the above and simply passes the name of the Activity class as the name parameter. This means that it should really be used only for this Activity to store its own internal settings, and not for preferences that should be global for other components of the application.

In the case of BroadcastReceiver the onReceive(...) method is passed the Context parameter, so you can use context.getSharePreferences(<some_name>, <mode>) to get the SharedPreferences saved by the Activity .

+10
source
 public class AndroidWalkthroughApp4 extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public void onResume() { // get EditText object EditText editText = (EditText)this.findViewById(R.id.edit_text); // get preferences object SharedPreferences prefs = this.getPreferences(MODE_PRIVATE); // set text to our saved value editText.setText(String.valueOf(prefs.getInt("chars", 0))); // don't forget to do this, or your app will crash! super.onResume(); } @Override public void onPause() { // get EditText object EditText editText = (EditText)this.findViewById(R.id.edit_text); // get preferences object SharedPreferences prefs = this.getPreferences(MODE_PRIVATE); // create editor from preferences object SharedPreferences.Editor editor = prefs.edit(); // save and write length of EditText editor.putInt("chars", editText.getText().length()); editor.commit(); // don't forget this either! super.onPause(); } } 
0
source

All Articles