Why is this value null?

2020-04-10 10:47发布

问题:

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);

}

回答1:

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);
    }
}
}