android之-----SharedPreferences(存储数据)简单使用

作为Android的5大存储数据的方式之一,sharepreferences还是具有其鲜明的特点的。
1.存储的数据一般比较小,比如是android的配置信息,用户名和密码之类的信息。
2.使用简单,不像操作数据库那么麻烦,写sql语句之类的。
3.采用键值对的形式存储数据。
下面是写在活动中的sharepreferences:

private TextView text;  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  

        text = (TextView) findViewById(R.id.text);  
        // 新建文件  
        SharedPreferences share = getSharedPreferences("test", 0);  
        // 处于能编辑状态  
        SharedPreferences.Editor edit = share.edit();  
        // 传入键值对  
        edit.putString("w", "suzhen");  
        edit.putInt("e", 1);  
        // 提交  
        edit.commit();  
        // 获取数据  
        String fir = share.getString("w", "");  
        int sec = share.getInt("e", 0);  

        text.setText(fir + "*****" + sec);  
    }  

效果很简单,是在textview中打印存储的两个数据。
下面给大家讲下在非ui线程中访问sharepreferences:

[java] view plain copy print?
private TextView text;  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  

        text = (TextView) findViewById(R.id.text);  
        GetShare share = new GetShare(this);  
        share.init();  
        String fir = share.getString();  
        int sec = share.getInt();  

        text.setText(fir + "*****" + sec);  
    }  

先建个类,其中写明sharepreferences的新建和返回值:

public class GetShare {  
    private Context context;  
    private SharedPreferences share;  

    /* 
     * 初始化对象 
     */  
    public GetShare(Context context) {  
        this.context = context;  
    }  

    public void init() {  
        // 新建文件  
        share = context.getSharedPreferences("test", 1);  
        // 处于能编辑状态  
        SharedPreferences.Editor edit = share.edit();  
        // 传入键值对  
        edit.putString("w", "hello");  
        edit.putInt("e", 1);  
        // 提交  
        edit.commit();  

        Toast.makeText(context, share.getString("w", ""), 1000);  
    }  

     public String getString() {  
     return share.getString("w", "");  
     }  

     public int getInt() {  
     return share.getInt("e", 11);  
     }  
}  

这样 ,就可以在需要的时候,在ui线程中访问这个类,从而来访问相关的数据。
不懂的可以留言或者私聊博主

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值