Android中的SharedPreferences存储数据方式

1.概述。SharePreferences是用来存储一些简单配置信息的一种机制,使用Map数据结构来存储数据,以键值对的方式存储,采用了XML格式将数据存储到设备中。例如保存登录用户的用户名和密码。只能在同一个包内使用,不能在不同的包之间使用,其实也就是说只能在创建它的应用中使用,其他应用无法使用。

创建的存储文件保存在/data/data/<package name>/shares_prefs文件夹下。

 

 

2.使用。
通过Context.getSharedPreferences方法获取SharedPreferences对象,参数分别为存储的文件名和存储模式。

  1. // 获取SharedPreferences对象  
  2. SharedPreferences sp = getSharedPreferences(DATABASE, Activity.MODE_PRIVATE);  
  3. // 获取Editor对象  
  4. Editor editor = sp.edit();  

 

3.操作。SharePreferences存储数据是通过获取Editor编辑器对象来操作的。
插入数据:
调用Editor.putxxxx方法,两个参数分别为键和值。
获取数据:
调用Editor.getxxxx方法,两个参数分别为键和不存在指定键时的默认值。
删除数据:
调用Editor.remove方法,参数为指定的键。
清空所有数据:
调用Editor.clear方法
上述所有方法调用都要执行Editor.commit方法来提交。

 

下面通过对数据的增删改查来演示下SharePreferences的使用。

/**
 * MainActivity
 *
 * @author zuolongsnail
 */
public class MainActivity extends Activity {
    private EditText keyET;
    private EditText valueET;
    private Button insertBtn;
    private Button deleteBtn;
    private Button modifyBtn;
    private Button queryBtn;
    private Button clearBtn;
    private TextView textView;
    /** 存储的文件名 */
    public static final String DATABASE = "Database";
    /** 存储后的文件路径:/data/data/<package name>/shares_prefs + 文件名.xml */
    public static final String PATH = "/data/data/code.sharedpreferences/shared_prefs/Database.xml";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        keyET = (EditText) findViewById(R.id.key);
        valueET = (EditText) findViewById(R.id.value);
        insertBtn = (Button) findViewById(R.id.insert);
        deleteBtn = (Button) findViewById(R.id.delete);
        modifyBtn = (Button) findViewById(R.id.modify);
        queryBtn = (Button) findViewById(R.id.query);
        clearBtn = (Button) findViewById(R.id.clear);
        // 用于显示存储文件中数据
        textView = (TextView) findViewById(R.id.content);
        insertBtn.setOnClickListener(new OperateOnClickListener());
        deleteBtn.setOnClickListener(new OperateOnClickListener());
        modifyBtn.setOnClickListener(new OperateOnClickListener());
        queryBtn.setOnClickListener(new OperateOnClickListener());
        clearBtn.setOnClickListener(new OperateOnClickListener());
    }

    class OperateOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            // 获取SharedPreferences对象
            SharedPreferences sp = getSharedPreferences(DATABASE,
                    Activity.MODE_PRIVATE);
            // 获取Editor对象
            Editor editor = sp.edit();
            //  获取界面中的信息
            String key = keyET.getText().toString();
            String value = valueET.getText().toString();
            switch (v.getId()) {
            // 插入数据
            case R.id.insert:
                editor.putString(key, value);
                editor.commit();
                textView.setText(MainActivity.this.print());
                break;
            // 删除数据
            case R.id.delete:
                editor.remove(key);
                editor.commit();
                textView.setText(MainActivity.this.print());
                break;
            // 修改数据
            case R.id.modify:
                editor.putString(key, value);
                editor.commit();
                textView.setText(MainActivity.this.print());
                break;
            // 查询数据
            case R.id.query:
                String result = sp.getString(key, "");
                textView.setText("key=" + key + ",value=" + result);
                break;
            // 清空所有数据
            case R.id.clear:
                editor.clear();
                editor.commit();
                textView.setText(MainActivity.this.print());
                break;
            }

        }
    }

    /** 获取存储文件的数据 */
    private String print() {
        StringBuffer buff = new StringBuffer();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(PATH)));
            String str;
            while ((str = reader.readLine()) != null) {
                buff.append(str + "/n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buff.toString();
    }

}

程序截图: 

下面提供一个SharedPreferences工具类,在开发中直接调用即可。

/**
 * SharedPreferences存储数据方式工具类
 * @author zuolongsnail
 */
public class SharedPrefsUtil {
    public final static String SETTING = "Setting";
    public static void putValue(Context context,String key, int value) {
         Editor sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE).edit();
         sp.putInt(key, value);
         sp.commit();
    }
    public static void putValue(Context context,String key, boolean value) {
         Editor sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE).edit();
         sp.putBoolean(key, value);
         sp.commit();
    }
    public static void putValue(Context context,String key, String value) {
         Editor sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE).edit();
         sp.putString(key, value);
         sp.commit();
    }
    public static int getValue(Context context,String key, int defValue) {
        SharedPreferences sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);
        int value = sp.getInt(key, defValue);
        return value;
    }
    public static boolean getValue(Context context,String key, boolean defValue) {
        SharedPreferences sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);
        boolean value = sp.getBoolean(key, defValue);
        return value;
    }
    public static String getValue(Context context,String key, String defValue) {
        SharedPreferences sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);
        String value = sp.getString(key, defValue);
        return value;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.bdvcd.app.utils; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; /** * 文件名:SharedPrefsUtil.java App存储数据工具类 * 版本信息:V1.0 * 日期:2013-03-11 * Copyright BDVCD Corporation 2013 * 版权所有 http://www.bdvcd.com */ public class SharedPrefsUtil { /** 数据存储的XML名称 **/ public final static String SETTING = "bdvcd"; /** * 存储数据(Long) * * @param context * @param key * @param value */ public static void putLongValue(Context context, String key, long value) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.putLong(key, value); sp.commit(); } /** * 存储数据(Int) * * @param context * @param key * @param value */ public static void putIntValue(Context context, String key, int value) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.putInt(key, value); sp.commit(); } /** * 存储数据(String) * * @param context * @param key * @param value */ public static void putStringValue(Context context, String key, String value) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.putString(key, value); sp.commit(); } /** * 存储数据(boolean) * * @param context * @param key * @param value */ public static void putBooleanValue(Context context, String key, boolean value) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.putBoolean(key, value); sp.commit(); } /** * 取出数据(Long) * * @param context * @param key * @param defValue * @return */ public static long getLongValue(Context context, String key, long defValue) { SharedPreferences sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE); long value = sp.getLong(key, defValue); return value; } /** * 取出数据(int) * * @param context * @param key * @param defValue * @return */ public static int getIntValue(Context context, String key, int defValue) { SharedPreferences sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE); int value = sp.getInt(key, defValue); return value; } /** * 取出数据(boolean) * * @param context * @param key * @param defValue * @return */ public static boolean getBooleanValue(Context context, String key, boolean defValue) { SharedPreferences sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE); boolean value = sp.getBoolean(key, defValue); return value; } /** * 取出数据(String) * * @param context * @param key * @param defValue * @return */ public static String getStringValue(Context context, String key, String defValue) { SharedPreferences sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE); String value = sp.getString(key, defValue); return value; } /** * 清空所有数据 * * @param context * @param key * @param defValue * @return */ public static void clear(Context context) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.clear(); sp.commit(); } /** * 清空所有数据 * * @param context * @param key * @param defValue * @return */ public static void remove(Context context, String key) { Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE) .edit(); sp.remove(key); sp.commit(); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值