Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences from different activity

Tags:

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?

like image 578
user1390816 Avatar asked Jul 03 '12 18:07

user1390816


People also ask

Is SQLite better than SharedPreferences?

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.

Is SharedPreferences deprecated?

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


1 Answers

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.

like image 88
ρяσѕρєя K Avatar answered Oct 04 '22 22:10

ρяσѕρєя K