I load from activity A the SharedPreferences in following way:
private void SavePreferences(String key, String value){
SharedPreferences sharedPreference
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.
To store values in shared preferences:
SharedPreferences preferences==PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("Name","Harneet");
editor.commit();
To retrieve values from shared preferences:
SharedPreferences preferences==PreferenceManager.getDefaultSharedPreferences(this);
String name=preferences.getString("Name","");
if(!name.equalsIgnoreCase(""))
{
name=name+" Sethi"; /* Edit the value here*/
}
To edit data from sharedpreference
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.commit();
To retrieve data from shared preference
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null)
{
//mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
/*if (selectionStart != -1 && selectionEnd != -1)
{
mSaved.setSelection(selectionStart, selectionEnd);
}*/
}