I load from activity A the SharedPreferences in following way:
private void SavePreferences(String key, String value){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(key, value); editor.commit(); }
At activity B I want to load the SharedPreferences. Following was a NullPointerException:
private void LoadPreferences(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); data = sharedPreferences.getString("name", "08:00") ; }
If I try following, I get this compilation error: "No enclosing instance of the type A is accessible in scope"
private void LoadPreferences(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(A.this); data = sharedPreferences.getString("name", "08:00") ; }
How can I access the data?
To give an example, SharedPreferences are useful for storing user preferences, where there are just a handful of variables that need storing. SQLite on the other hand would be better for storing data where there is a large set of items, such as song titles in a music library which need to be searched through.
getSharedPreferencesMode. Deprecated: Deprecated in Java. Returns the current mode of the SharedPreferences file that preferences managed by this will use. The mode that can be passed to Context#getSharedPreferences(String, int) .
use getApplicationContext()
instead of this
in both Activities as:
In activity A the SharedPreferences in following way:
private void SavePreferences(String key, String value){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(key, value); editor.commit(); Intent sd=new Intent(this,Secongtess.class); startActivity(sd); }
and in Activity B get Value as:
private void LoadPreferences(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String data = sharedPreferences.getString("name", "08:00") ; Toast.makeText(this,data, Toast.LENGTH_LONG).show(); }
because as doc says:
getDefaultSharedPreferences(Context context) :
Gets a SharedPreferences instance that points to the default file that is used by the preference framework in the given context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With