sharedpreferencces的使用

package cn.itcast.preference;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class DemoActivity extends Activity implements OnClickListener {
	private EditText mEtName;
	private EditText mEtPwd;
	private Button mBtLogin;
	private CheckBox mCb;
	private SharedPreferences sp; // 用来保存参数的接口 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		mEtName = (EditText) this.findViewById(R.id.et_name);
		mEtPwd= (EditText) this.findViewById(R.id.et_pwd);
		mBtLogin = (Button) this.findViewById(R.id.bt_login);
		mCb = (CheckBox) this.findViewById(R.id.cb_remember_pwd);
		
        // 初始化 sharedpreference 
        sp = this.getSharedPreferences("config.txt", Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE);
        //sp.getString的第二个参数是如果sp里面没有数据的话,给他的默认值.
		//sp.getBoolean("issetup", false);如果没有找到issetup这个键的值为false.
        boolean issetup = sp.getBoolean("issetup", false);
        if(issetup){
        	String name = sp.getString("name", "");
        	String pwd = sp.getString("pwd", "");
        	mEtName.setText(name);
        	mEtPwd.setText(pwd);
        }
        

		mBtLogin.setOnClickListener(this);
    }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_login:
			String name  =mEtName.getText().toString().trim();
			String pwd = mEtPwd.getText().toString().trim();
			// 得到sharedpreference的编辑器 
			Editor editor =  sp.edit();
			editor.putString("name", name);
			editor.putString("pwd", pwd);
			editor.putBoolean("issetup", true);
			// 清空编辑器里面的内容 
			// editor.clear();
			
			// 非常重要
			editor.commit();
			Toast.makeText(this, "保存密码成功", Toast.LENGTH_SHORT).show();
			break;

		}
		
	}
}

你可能感兴趣的:(sharedpreferencces的使用)