zoukankan      html  css  js  c++  java
  • Android

    Shared Preference (分享首选项) 具体解释


    本文地址: http://blog.csdn.net/caroline_wendy/article/details/24454963


    Shared Preference将一组原始数据的NVP(name-value pair)存储为命名首选项(named preference).


    创建SharedPreferences类使用getSharedPreferences(), 并传入要SharedPreferences的名称;


    改动SharedPreferences类使用SharedPreferences.Editor类, 通过调用SharedPreferences类的edit()方法, 获取对象;

    使用SharedPreferences.Editor类的put<type>()方法进行改动相关的名称(name)的值(value);

    使用SharedPreferences.Editor类的apply()方法进行异步保存;

    注意:保存能够使用apply()方法和commit()方法, 可是apply()方法是首选.

    apply()方法是异步保存, commit()方法是同步保存, 须要阻止调用线程, 推断返回, 所以优先选择apply()方法.


    訪问SharedPreferences类, 使用getSharedPreferences()方法, 即与创建类似;

    使用SharedPreferences类的get<type>()方法, 返回保存的值, 须要一个命名(name), 即键(key), 和一个默认值, 当没有值时使用默认.

    使用SharedPreferences类的getAll()方法, 返回全部映射, 能够通过contains()方法, 返回boolean类型, 推断是否存在.


    详细參考Android API: http://[防禁用]developer.android.com/guide/topics/data/data-storage.html


    代码:

    package mzx.spike.earthquake.app;
    
    import android.app.Activity;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    
    import java.util.Map;
    
    /**
     * Created by Spike on 2014/4/25.
     */
    public class Test extends Activity {
        public static final String MY_PREFS = "MyPrefs";
    
        @Override
        protected void onCreate(Bundle state){
            super.onCreate(state);
    
            // Restore preferences
            SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS, Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = mySharedPreferences.edit();
    
            editor.putBoolean("isTrue", true);
            editor.putFloat("lastFloat", 1f);
            editor.putInt("wholeNumber", 2);
            editor.putLong("aNumber", 31);
            editor.putString("textEntryValue", "Not Empty");
    
            editor.commit();
    
            boolean isTrue = mySharedPreferences.getBoolean("isTrue", false);
            float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f);
            int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1);
            long aNumber = mySharedPreferences.getLong("aNumber", 0);
            String textEntryValue = mySharedPreferences.getString("textEntryValue", "");
    
            Map<String, ?

    > allPreferences = mySharedPreferences.getAll(); boolean containsLastFloat = mySharedPreferences.contains("lastFloat"); } }








  • 相关阅读:
    并查集N(The Suspects)
    (并查集)Ubiquitous Religions
    (并查集)How Many Tables
    并查集(畅通工程)
    约瑟夫环(栈和队列)
    队列-排队买饭
    栈的基本操作
    双向队列
    括号匹配
    Queue
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5329709.html
Copyright © 2011-2022 走看看