zoukankan      html  css  js  c++  java
  • android 数据存储操作之 SharedPreferences

    android的数据存储方式有

    1.SharedPreferences

    2.文件存储

    3.SQLite存储

    4.内容提供器(Content provider)

    5.网络

    1.SharedPreferences

    是android用来提供用来存储简单的配置信息的一种方式。是一种key/value关系的数据类型,数据保存在一个xml文件中

    首先需要创建一个SharedPreferences对象

     SharedPreferences s=getSharedPreferences("filename", 0);

    其中 第一个参数为保存的文件名,在FileExplorer中/data/data/包名/shared_prefs下可以看到对应的文件

    读文件 :

    s.getString("name", "")

    第一个参数为key 第二个为默认值;

        当然还有对应的不同的获取值的方式

    image

    写文件:

    s.edit()
     .putString("name", edit_name.getText().toString())
     .commit();

    s.edit()表示进入编辑状态

    putString()压入值

    commit()提交内容

    同样put也有压入不同值的方式:

    image

    全部代码:

    public class main extends Activity {
    	
    	EditText edit_name;
    	Button but_sub;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            edit_name=(EditText)this.findViewById(R.id.edit_name);
            //获取一个SharedPreferences对象
            SharedPreferences s=getSharedPreferences("filename", 0);
           
            edit_name.setText(s.getString("name", "")); 
            but_sub=(Button)this.findViewById(R.id.but_sub);
            but_sub.setOnClickListener(new OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    			    SharedPreferences s=getSharedPreferences("filename", 0);
    				s.edit()
    				 .putString("name", edit_name.getText().toString()) 
    				 .commit();
    				
    			
    			}
    		}); 
        }
    }

    Preferences只能在同一包中使用,不能在不同的包使用,保存的数据以健值的方式明文保存,适合存储简单数据类型。

  • 相关阅读:
    10gen发布MongoDB增量备份服务
    JSON.NET 5中的架构变更
    Snowbox 2.0 发布,POP3 邮件服务器
    资源监控工具 glances
    Druid 0.2.18 发布,阿里巴巴数据库连接池
    Groovy 更新到 2.0.8 and 2.1.3
    Apache Libcloud 0.12.4 发布,统一云计算接口
    Go1.1性能测试报告(和C差距在10%以内)
    Apache Camel 2.11.0 发布,规则引擎
    2010年01月01日0时0分 总结我的2009
  • 原文地址:https://www.cnblogs.com/ac1985482/p/2068432.html
Copyright © 2011-2022 走看看