Android数据保存之SharedPreference

SharedPreference 非常适合用来保存零散的简单的数据,如用户名和密码等

package com.test.storage;

import android.app.Activity;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.os.Bundle;

import android.view.View;

import android.widget.TextView;

public class SharePreferenceDemo extends Activity{

    private TextView et_name;

    private TextView et_password;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    // TODO Auto-generated method stub

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        SharedPreferences sp = getSharedPreferences("info",MODE_PRIVATE);

    //获取数据 第一个参数为存储的字符串的值,第二个参数是设置没取到对应的数据时,默认显示的值

        String name = sp.getString("name""");

        String password = sp.getString("password""");

        et_name = (TextViewthis.findViewById(R.id.name);

        et_password = (TextViewthis.findViewById(R.id.password);

        et_name.setText(name);

        et_password.setText(password);

    }

    public void click(View v){

    //路径在data/data/程序标示包名/shared_prefs/

    //不用为文件添加后缀名,添加也是无效的.数据是保存在xml中。

        String name = et_name.getText().toString().trim();

        String password = et_password.getText().toString().trim();

         SharedPreferences sp = getSharedPreferences("info"MODE_PRIVATE);

     //获取sp的编辑器

         Editor editer = sp.edit();

      //通过编辑器存放数据

         editer.putString("name", name);

         editer.putString("password", password);

         //提交,保存的数据需要提交才能生效。

        editer.commit();

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值