Android 的資料儲存方法有以下5 種:
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.

(1) Shared Preferences

Shared Preferences 也有分2種:

getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.  (這一個是可以用在不同的Activity 層面上,就是說如果需要在應用程序中多個Activity之間分享同一個SharedPreferences對象時,就用這一個)

如果是只需要在同一個Actiticy內使用,就可以用下面這一個不用加名稱的getPreferences.

getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

寫入時:

(1) 如果是使用SharedPreferences 提供名稱

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);      

(2) 做用 edit() 開啟 SharedPreferences.Editor

SharedPreferences.Editor editor = settings.edit();       

(3) 使用 putBoolean() or putString() methods 將需要儲存的資料存入editor

editor.putBoolean("silentMode", mSilentMode);

(4) 最後記得要commit 

editor.commit();

讀取時:

只需要用 getBoolean() or getString() methods 就可以了。

 

public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean silent = settings.getBoolean("silentMode", false);
       setSilent(silent);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
    }
}
 
文章標籤
創作者介紹

呆子獅的夢想世界

lionlionchopper 發表在 痞客邦 PIXNET 留言(0) 人氣()