Android_SharedPreferences用户偏好设置

来源:互联网 发布:淘宝上有没有微信号卖 编辑:程序博客网 时间:2024/05/15 23:43
package com.baidu.userpreferences;import android.os.Bundle;import android.app.Activity;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {private Button saveButton = null;private EditText usernameText = null;private EditText passwordText = null;private SharedPreferences preferences  = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);usernameText = (EditText) this.findViewById(R.id.username);passwordText = (EditText) this.findViewById(R.id.password);saveButton= (Button) this.findViewById(R.id.save);/* * 得到首选项对象,第一个参数为首选项的名称(test.xml文件),首选项文件的文件模式类型,实际上就是xml保存和读写的简化操作 * 以test命名的xml文件存放在 data/data/<package name>/shared_prefs目录下 */preferences = this.getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE);showPreferences();//如果首选项文件已经保存过,将执行执行初始化saveButton.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {String username = usernameText.getText().toString();String password = passwordText.getText().toString();if(username.equals("") || password.equals("")){show("用户名或者密码不能为空!");return;}Editor editor = preferences.edit();//在对首选项执行编辑前,应该取得该首选项对象的编辑器editor.putString("username", username);//对编辑器执行编辑操作editor.putString("password", password);editor.commit();//将内存中的数据提交show("保存首选项成功!");}});}public void showPreferences(){//如果参数很多,可以使用Map集合,用于存储键值对String username = preferences.getString("username", "");//第一个参数为name,第二个如果不存在默认值String password = preferences.getString("password", "***");usernameText.setText(username);passwordText.setText(password);}/** * 提示消息 * @param info */public void show(String info){Toast.makeText(this, info, Toast.LENGTH_SHORT).show();}}