Why Is This Value Null?
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
Solution 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
publicclassMainActivityextendsAppCompatActivity {
private SharedPreferences preferences;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editoreditor= preferences.edit();
editor.putString("Status","Success");
editor.apply();
getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true,
newVolumeCheck(this, newHandler()));
}
}
import android.content.Context;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
publicclassVolumeCheckextendsContentObserver {
privatefinal SharedPreferences preferences;
private Context context;
publicVolumeCheck(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());
Stringstatus= preferences.getString("Status", "");
if(!status.equalsIgnoreCase(""))
{
// got the value read from shared preference
Log.i("Reading value", status);
}
}
}
Post a Comment for "Why Is This Value Null?"