[Android] 使用JSON和SharedPreferences儲存使用者自訂類

來源:互聯網
上載者:User

標籤:

先看一下Google官方對於SharedPreferences的定義:

The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

SharedPreferences可以用來永久地儲存資料,即使應用被銷毀。事實上資料存放區在Android的內部儲存空間上。

有兩種分方法用來擷取SharedPreferences對象。 getSharedPreferences() - 當應用需要多個由名字區分的隱藏檔時,可以調用這個方法。getPreferences()-當應用只需要一個隱藏檔時,調用這個方法。

在SharedPreferences對象中寫入資料,需要:

1.調用edit()方法獲得一個SharedPreferences.Editor對象。

2.使用Editor對象的方法比如putBoolean()和putString()等將資料寫入Editor。

3.使用Editor對象的方法commit()或apply()將資料提交。

讀取SharedPreferences中的資料只需要調用SharedPreferences的方法如getBoolean()和getString().

下面是一個使用SharedPreferences儲存資料的例子。

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();    }}

 

從Google的介紹中可以看到,SharedPreferences的局限性在於只能儲存基本類型:boolean,floot,short,int,long,string等。對於使用者自訂的類型,通常由多個基本類型資料和數組組成。比如這樣一個自訂類型:

public class Action {    // Action Data    private UUID id;    private Date start;private String actionName;    private int alarmingHour=0;private String[] records = new String[100];}

這時候就不能使用SharedPreferences來儲存。

這個時候就需要另一個主角 :JSON.

JSON的全稱是JavaScript對象標記法,是儲存和交換文本資訊的文法,類似 XML,實現了對象與文本之間的轉化。

在Android中內建了JSONObject和JSONArray.

對於這樣一個使用者自訂類型,可以通過

    /**     * transform the Action instance to JSONObject,and then save JSONObject.toString()     * to SharedPreference.     * @return the JSONObject corresponding to the Action     * @throws JSONException     */    public JSONObject toJSON() throws JSONException{        JSONObject json = new JSONObject();        json.put(JSON_id,id.toString());        json.put(JSON_startDate, start.getTime());        JSONArray array = new JSONArray();        JSONObject JSONRecords[] = new JSONObject[length];        for(int i = 0; i<length;i++){            JSONRecords[i] = new JSONObject();            JSONRecords[i].put(JSON_record, records[i].getRecord());            array.put(i,JSONRecords[i]);        }        json.put(JSON_dailyRecords,array);        return json;    }/**     * get the Action from JSONObject     * @param jsonString the jsonString retrieved from SharedPreference.     * @return the Action stored in JSONObject     * @throws JSONException     */    public static Action parseJSONString(String jsonString) throws JSONException{        JSONObject json;        json = new JSONObject(jsonString);        UUID id = UUID.fromString(json.getString(JSON_id));        Date start = new Date(json.getLong(JSON_startDate));        String actionName = json.getString(JSON_name);        String[] dailyRecords = new DailyRecord[100];        for (int i = 0; i<100;i++){            JSONObject json_record = array.getJSONObject(i);            String record = json_record.getString(JSON_record);            dailyRecords[i] = record;        }        return new Action(id,start,actionName,dailyRecords);    }

來實現Action和JSONObject之間的轉換,JSONObject實際是是文本的形式,可以很方便地轉化為String,因此使用SharedPreferences來儲存轉換之後的String就可以實現Action的儲存。

SharedPreferences sp =getSharedPreferences(Config.CurrentAction, Context.MODE_PRIVATE);SharedPreferences.Editor editor = sp.edit();try {    editor.putString(Config.CurrentActionDetails, currentAction.toJSON().toString());} catch (JSONException e) {    e.printStackTrace();}editor.apply();

從SharedPreferences中讀取Action可以這樣做:

try {                SharedPreferences sp = getSharedPreferences(Config.CurrentAction, Context.MODE_PRIVATE);                String jsonString = sp.getString(Config.CurrentActionDetails, "");                currentAction = Action.parseJSONString(jsonString);            } catch (JSONException e) {                e.printStackTrace();            }

這樣就實現了使用者自訂類Action的本機存放區與讀取。

[Android] 使用JSON和SharedPreferences儲存使用者自訂類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.