代码改变世界

Android SharedPreferences 存储用户登录密码

2011-05-17 15:24  闫妍  阅读(353)  评论(0编辑  收藏  举报

SharedPreferences 存储是在手机上的名字对存储,以XML 文件的形式。

 

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;

public class DBSharedPreferences extends Activity {
    public static final String SETTING_INFOS = "SETTING_Infos"; //这个就是XML文件名
    public static final String NAME = "NAME";
    public static final String PASSWORD = "PASSWORD";
   
    private EditText field_name;
    private EditText filed_pass;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Find VIew
        field_name = (EditText) findViewById(R.id.name);
        filed_pass = (EditText) findViewById(R.id.password);
        // Restore preferences
        SharedPreferences settings = getSharedPreferences(SETTING_INFOS, 0); //获取SharedPreferences 对象
        String name = settings.getString(NAME, ""); //读内容
        String password = settings.getString(PASSWORD, "");
        //Set value
        field_name.setText(name);
        filed_pass.setText(password);

    }
   

//重载关闭事件
    @Override
    protected void onStop(){
        super.onStop();
        SharedPreferences settings = getSharedPreferences(SETTING_INFOS, 0);
        settings.edit()
            .putString(NAME, field_name.getText().toString()) //写内容
            .putString(PASSWORD, filed_pass.getText().toString())
            .commit();
    }
}