Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get SharedPreferences from a service

I am trying to access shared preferences from a service. I have used the the following to save the value of text to a string...

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Ignore1_value", Example.getText().toString());
editor.commit();

But, how would i get the value in a service? Everything i have tried returns as nothing. Any help would be perfect and much appreciated?

I looked through some other questions as well with no solution. I have came up with this, but like i said it returns it as no text.

Context ctx = getApplicationContext();
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ctx);
    String example1string = sharedPreferences.getString("Ignore1_value","");
    Log.i("**GetSettings", example1string);
like image 248
user1190019 Avatar asked Jul 07 '12 18:07

user1190019


Video Answer


1 Answers

I'm always using PreferenceManager.getDefaultSharedPreferences(context). This is the same for all Contexts in your application.

A Service is a Context itself, so this would be sufficient:

PreferenceManager.getDefaultSharedPreferences(this);
like image 94
nhaarman Avatar answered Sep 21 '22 04:09

nhaarman