Why is this value null?

前端 未结 1 919
梦毁少年i
梦毁少年i 2021-01-21 01:52

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 share

相关标签:
1条回答
  • 2021-01-21 02:23

    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);
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题