3

I am succesfully making, saving, and retrieving my shared preferences from my mainActivity, but I cant get it from my service...

For some reason, my shared preferences is null when I try to retrieve it from a background service...

I initialize my preferences in onCreate:

contactsPrefs = getSharedPreferences("contactsPrefs", MODE_PRIVATE); //Making a shared preferences

Save values in onCreate:

    myEditor = contactsPrefs.edit();

    Set<String> set = new HashSet<String>();
    set.addAll(contactArrayList);

    myEditor.clear(); //Clearing current values in shared pref
    myEditor.putStringSet("contactSetKey", set); //Adding contacts
    myEditor.commit();

All this is going fine, but when I try to access my preferences from my service, I get null:

    preferences = PreferenceManager.getDefaultSharedPreferences(c); //See edit at bottom for more info

if(preferences.getStringSet("contactSetKey", null) != null) {
        contactArrayList.addAll(preferences.getStringSet("contactSetKey", null));

        for (String number : contactArrayList) {

            number.substring(number.indexOf("-") + 1); //Remove all characters before the hyphen from my string

            Log.v(TAG, number);

        }
    }else{
        Log.v(TAG, "Dagnabit it its null");
    }

And to my disappointment, I get the log Dagnabit it its null. why is it null? I can assure you that it works from my main activity, because I am able to display all of my data from my shared preferences when I access it from my shared preference. So I know that it shouldn't be null...But it is for some reason

Thanks,

Ruchir

EDIT:

I actually register a volume listener using content observer, and I am accesing the preferences from there. Here is in the service:

 mSettingsContentObserver = new volumeCheck(this, new Handler());
        getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);

Here is the Content Observer:

   public class volumeCheck extends ContentObserver {

 public volumeCheck(Context c, Handler handler) {
        super(handler); //Creates a new handler
        context = c; //variable context, defined earlier, is set equal to c, context of service.

        preferences = PreferenceManager.getDefaultSharedPreferences(c);

}
Ruchir Baronia
  • 7,406
  • 5
  • 48
  • 83

1 Answers1

0

Try to get shared pref reference using application context as shown below:

contactsPrefs = 
          getApplicationContext().getSharedPreferences("contactsPrefs", 
          MODE_PRIVATE); //Making a shared preferences

Note: If you still getting null, then get the shared preference from onStart() method of the service instead of doing it inside onCreate().

EDIT: I tested and its working

public class MainActivity extends AppCompatActivity {

private SharedPreferences preferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("Status","Success");
    editor.apply();

    getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true,
            new VolumeCheck(this, new Handler()));
}
}



import android.content.Context;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;


public class VolumeCheck extends ContentObserver {
private final SharedPreferences preferences;

private Context context;

public VolumeCheck(Context c, Handler handler) {
    super(handler); //Creates a new handler
    context = c; //variable context, defined earlier, is set equal to c, context of service.

    preferences = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext());
    String status = preferences.getString("Status", "");
    if(!status.equalsIgnoreCase(""))
    {
        // got the value read from shared preference
        Log.i("Reading value", status);
    }
}
}
Guru_VL
  • 402
  • 3
  • 6
  • Please see my edit of my question, it is in a service in a listener. Is that okay? – Ruchir Baronia Feb 11 '16 at 01:14
  • The code should be like below @Override public int onStartCommand(Intent intent, int flags, int startId) { contactsPrefs = getApplicationContext().getSharedPreferences("contactsPrefs", MODE_PRIVATE); //Making a shared preferences return super.onStartCommand(intent, flags, startId); } – Guru_VL Feb 11 '16 at 01:21
  • Did you see my edit? It is actually in a content observer, so I get `Cannot resolve getApplicationContext()`. – Ruchir Baronia Feb 11 '16 at 01:26
  • Look at the bottom of my question – Ruchir Baronia Feb 11 '16 at 01:26
  • oh, you are passing a context reference to the content observer, you can use it to get the shared preference. – Guru_VL Feb 11 '16 at 01:30
  • How? Can you show me? BTW: The context is passed in from the service, where I register the listener. It is in the bottom of my question. Please let me know how to do it? – Ruchir Baronia Feb 11 '16 at 01:38
  • Please check edited answer with the sample code which i tested and its working. – Guru_VL Feb 11 '16 at 01:50
  • Awesome, it worked! For some reason though, my `number.substring(number.indexOf("-") + 1); //Remove all characters before the hyphen from my string` is not working. How can I remove everything before the `-`? – Ruchir Baronia Feb 11 '16 at 02:00
  • Okay, but why is the hyephen not removing – Ruchir Baronia Feb 11 '16 at 03:27