zoukankan      html  css  js  c++  java
  • SharedPreferences的用法

    在Android开发过程中,有时候我们需要保存一些简单的软件配置等简单数据的信息,而如果我们直接用数据库存储的话又不太方便,在这里我们就可以用到SharedPreferences,SharedPreferences保存的数据主要是类似于配置信息格式的数据,因此保存的数据主要是简单类型的键值对(key-value),它保存的是一个XML文件。其存储位置在/data/data/<包名>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。

    SharedPreferences是一个接口,程序是无法创建SharedPreferences实例的,可以通过Context.getSharedPreferences(String name.int mode)来得到一个SharedPreferences实例

    name:是指文件名称,不需要加后缀.xml,系统会自动为我们添加上。一般这个文件存储在/data/data/<package name>/shared_prefs下(这个面试常问到)

    mode:是指定读写方式,其值有三种,分别为:

    Context.MODE_PRIVATE:指定该SharedPreferences数据只能被本应用程序读、写

    Context.MODE_WORLD_READABLE:指定该SharedPreferences数据能被其他应用程序读,但不能写

    Context.MODE_WORLD_WRITEABLE:指定该SharedPreferences数据能被其他应用程序读写。

    package cn.test.service;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    
    public class PreferencesService {
        private Context context;
        
        public PreferencesService(Context context) {
            this.context = context;
        }
        /**
         * 保存参数
         * @param name 姓名
         * @param age 年龄
         */
        public void save(String name, Integer age) {
            SharedPreferences preferences = context.getSharedPreferences("itcast", Context.MODE_PRIVATE); 
            Editor editor = preferences.edit();
            editor.putString("name", name);
            editor.putInt("age", age);
            editor.commit();
        }
        /**
         * 获取各项配置参数
         * @return
         */
        public Map<String, String> getPreferences(){
            Map<String, String> params = new HashMap<String, String>();
            SharedPreferences preferences = context.getSharedPreferences("itcast", Context.MODE_PRIVATE);
            params.put("name", preferences.getString("name", ""));
            params.put("age", String.valueOf(preferences.getInt("age", 0)));
            return params;
        }
    }
  • 相关阅读:
    第39周星期日中秋节杂记
    php array_multisort
    php统计近一周和近30天的用户数据
    什么是CGI、FastCGI、PHPCGI、PHPFPM、SpawnFCGI?
    PHP array_multisort()函数超详细理解
    微博第三方登陆请求授权出现错误码:21322(重定向地址不匹配)的解决方法
    艾伟_转载:C# 反射技术应用 狼人:
    艾伟_转载:HttpApplication的认识与加深理解 狼人:
    艾伟_转载:C# .NET学习经验总结 狼人:
    艾伟_转载:C# 委托的同步调用和异步调用 狼人:
  • 原文地址:https://www.cnblogs.com/xiang1336/p/3736883.html
Copyright © 2011-2022 走看看