`

android:SharedPreferences 保存数据(适合于保存上一次用户名与密码)

 
阅读更多
转自:http://doublekj.blog.163.com/blog/static/14681847420118465327617/

 

 

 

       // 当你第一次登录时,输入用户名、密码之后,按“登录”键,在其onclick函数中:

 

       // 保存用户名与密码

 

        Username = (EditText) findViewById(R.id.mainEdit_01);        //编辑框对象
        Password = (EditText) findViewById(R.id.mainEdit_02);

 

         User = Username.getText().toString();              
         Psw = Password.getText().toString();

 

        SharedPreferences preference = getSharedPreferences("person",Context.MODE_PRIVATE);

 

        Editor edit = preference.edit();

 

        edit.putString("User",User);      

 

        edit.putString("Psw",Psw);

 

        edit.commit();

 

       //在主界面初始化时,加载上一次保存的用户名与密码

 

        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

 

        Username = (EditText) findViewById(R.id.mainEdit_01);        //编辑框对象
        Password = (EditText) findViewById(R.id.mainEdit_02);

 

        SharedPreferences preference = getSharedPreferences("person",Context.MODE_PRIVATE);

 

        Username.setText(preference.getString("User",""));            //preference.getString(标示符,默认值<这里为空>)
        Password.setText(preference.getString("Psw", ""));

注意:这里的preference要分开定义,不能用同一个preference,不然无法生效

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics