Differences Between Methods apply()and commit() ● boolean commit() o Returns a boolean value to indicate if the new values were successfully written to persistent storage. o Writes its preferences out to persistent storage synchronously (can block the Ul thread) ·void apply() o Commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk. o does not block the Ul thread,but you won't be notified of any failures. Use apply()if you don't care about the return value and you're using this from your application's Ul thread. http://developer.android.com/reference/android/content/SharedPreferences.Editor.html 16
Differences Between Methods apply() and commit() • boolean commit() o Returns a boolean value to indicate if the new values were successfully written to persistent storage. o Writes its preferences out to persistent storage synchronously (can block the UI thread) • void apply() o Commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk. o does not block the UI thread, but you won’t be notified of any failures. Use apply() if you don't care about the return value and you’re using this from your application’s UI thread. http://developer.android.com/reference/android/content/SharedPreferences.Editor.html 16
public class Example extends Activity /Create a preference file with the name specified public static final String PREFS NAME "MyPrefsFile"; @Override protected void onCreate(Bundle state){ super.onCreate(state); 。。。 /Restore the preferences //Get the preference with the name specified SharedPreferences settings getsharedPreferences(PREFS_NAME,0); /Read the stored data from the preference int data settings.getInt("key",defaultvalue); } @Override protected void onStop(){ super.onstop(); /Store the preferences /We need an Editor object to make preference changes. SharedPreferences settings getsharedPreferences(PREFS_NAME,0); SharedPreferences.Editor editor settings.edit(); editor.putInt("key",value); /Commit the edits! editor.commit(); 17
17 public class Example extends Activity { // Create a preference file with the name specified public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onCreate(Bundle state){ super.onCreate(state); . . . // Restore the preferences // Get the preference with the name specified SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // Read the stored data from the preference int data = settings.getInt(“key", defaultValue); . . . } @Override protected void onStop(){ super.onStop(); // Store the preferences // We need an Editor object to make preference changes. SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putInt(“key”, value); // Commit the edits! editor.commit(); } }