Android数据之SharedPreferences储存

人的一生,总是难免有浮沉。不会永远如旭日东升,也不会永远痛苦潦倒。反复地一浮一沉,对于一个人来说,正是磨练。因此,浮在上面的,的,不必骄傲;沉在底下的,更用不着悲观。必须以率直、谦虚的态度,乐观进取、向前迈进。 —— 松下幸之助


本讲内容:SharedPreferences 数据储存(在博客androidUI介面(四)中使用到这数据储存)

Android的四种数据存储方式:
1、SharedPreferences
2、SQLite
3、ContentProvider
4、File


一、SharedPreferences的介绍

做软件开发应该都知道,很多软件会有配置文件,里面存放这程序运行当中的各个属性值,由于其配置信息并不多,如果采用数据库来存放并不划算,因为数据库连接跟操作等耗时大大影响了程序的效率,因此我们使用键值这种一一对应的关系来存放这些配置信息。SharedPreferences正是Android中用于实现这中存储方式的技术。


SharedPreferences的使用非常简单,能够轻松的存放数据和读取数据。SharedPreferences只能保存简单类型的数据,例如,String、int等。一般会将复杂类型的数据转换成Base64编码,然后将转换后的数据以字符串的形式保存在 XML文件中,再用SharedPreferences保存。


二、SharedPreferences使用方法:

要想使用SharedPreferences来存储数据,首先要获取到SharedPreferences对象Context类中提供了一个getSharedPreferences()方法用于创建一个SharedPreferences对象。此方法接收两个参数,第一个参数用于指定SharedPreferences文件的名称。SharedPreferences文件都是存放在/data/data/<packagename>/shared_prefs/目录下的。第二个参数用于指定操作模式。主要有两种模式可以选择,MODE_PRIVATE和MODE_MULTI_PROCESS。MODE_PRIVATE是默认的操作模式,和直接传入0效果相同,表示当前的应用程序才可以对这个SharedPreferences文件进行读写。MODE_MULTI_PROCESS一般用于会有多个进程中对同一个SharedPreferences文件进行读写的情况。得到SharedPreferences对象后,就可以向SharedPreferences文件中存储数据了,主要分三步实现。

1、调用SharedPreferences对象的edit()方法来获取一个SharedPreferences.Editor对象。

2、向SharedPreferences.Editor对象添加数据。

3、调用commit()方法将添加的数据提交,从而完成数据存储操作。


注意:由于SharedPreference是一个接口,而且在这个接口里并没有提供写入数据和读取数据的能力。但是在其内部有一个Editor内部的接口,Editor这个接口有一系列的方法用于操作SharedPreference。

示例一:将数据存储到SharedPreferences


运行程序,点击Save Data按钮,这时数据已经保存成功了,切换到DDMS->File Explorer /data/data/com.example.sharedpreferencestest/shared_prefs/目录下,可以看到生成了一个data文件


打开该文件


可以看到添加所有的数据都已经成功保存下来了,并且SharedPreferences文件是使用XML格式来对数据进行管理的

下面是res/layout/activity_main.xml 布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button 
        android:id="@+id/save_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save Data"/>

</RelativeLayout>

下面是MainActivity.java主界面文件:

public class MainActivity extends Activity {
	private Button saveData;
	
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        saveData=(Button) findViewById(R.id.save_data);
        saveData.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				SharedPreferences preferences=getSharedPreferences("data", MODE_APPEND);
				SharedPreferences.Editor editor=preferences.edit();
				editor.putString("name", "Dan");
				editor.putInt("age", 18);
				editor.putBoolean("married", false);
				editor.commit();
			}
		});
    }
}

示例二:从 SharedPreferences文件中读取数据


运行程序并点击按钮,然后查看LogCat中打印信息,所有之前存储的数据都成功读取出来了。


下面是MainActivity.java主界面文件:

public class MainActivity extends Activity {
	private static final String TAG="MainActivity";
	private Button restoreData;
	
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        restoreData=(Button) findViewById(R.id.restore_data);
        restoreData.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				SharedPreferences pref=getSharedPreferences("data", MODE_APPEND);
				String name=pref.getString("name", "");
				int age=pref.getInt("age", 20);
				boolean married=pref.getBoolean("married", false);
				Log.d(TAG, "name is "+name);
				Log.d(TAG, "age is "+age);
				Log.d(TAG, "married is "+married);
			}
		});
    }
}


示例三:实现记住密码功能

 

下面是res/layout/activity_login.xml 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/id_tv_top"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_alignParentTop="true"
        android:background="#ffe85628"
        android:gravity="center"
        android:text="登陆"
        android:textColor="@android:color/white"
        android:textSize="20sp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/id_tv_top"
        android:layout_margin="10dp" >

        <EditText
            android:id="@+id/id_et_account"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="@drawable/edit_selector"
            android:hint="请输入用户名"
            android:paddingLeft="20dp"
            android:paddingRight="10dp"
            android:singleLine="true"
            android:textColor="#ff444444"
            android:textColorHint="#ffcccccc"
            android:textSize="16sp" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/id_et_pwd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/id_et_account"
            android:layout_marginTop="10dp"
            android:background="@drawable/edit_selector"
            android:hint="请输入密码"
            android:inputType="textPassword"
            android:paddingLeft="20dp"
            android:paddingRight="10dp"
            android:singleLine="true"
            android:textColor="#ff444444"
            android:textColorHint="#ffcccccc"
            android:textSize="16sp" />
        
        <CheckBox 
            android:id="@+id/id_checkBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/id_et_pwd"
            android:text="记住密码"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/id_checkBox"
            android:layout_marginTop="20dp"
            android:orientation="horizontal"
            android:paddingLeft="10dp"
            android:paddingRight="10dp" >

            <Button
                android:id="@+id/id_login"
                android:layout_width="0dp"
                android:layout_height="48dp"
                android:layout_weight="1.0"
                android:background="@drawable/btn_selector"
                android:text="登陆"
                android:textColor="#ffffff"
                android:textSize="18sp" />

            <Button
                android:id="@+id/id_register"
                android:layout_width="0dp"
                android:layout_height="48dp"
                android:layout_marginLeft="20dp"
                android:layout_weight="1.0"
                android:background="@drawable/btn_selector"
                android:text="注册"
                android:textColor="#ffffff"
                android:textSize="18sp" />
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>


下面是res/layout/activity_register.xml 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/id_tv_top"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_alignParentTop="true"
        android:background="#ffe85628"
        android:gravity="center"
        android:text="注册"
        android:textColor="@android:color/white"
        android:textSize="20sp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/id_tv_top"
        android:layout_margin="10dp" >

        <EditText
            android:id="@+id/id_et_account_register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="@drawable/edit_selector"
            android:hint="请输入用户名"
            android:paddingLeft="20dp"
            android:paddingRight="10dp"
            android:singleLine="true"
            android:textColor="#ff444444"
            android:textColorHint="#ffcccccc"
            android:textSize="16sp" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/id_et_pwd_register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/id_et_account_register"
            android:layout_marginTop="10dp"
            android:background="@drawable/edit_selector"
            android:hint="请输入密码"
            android:inputType="textPassword"
            android:paddingLeft="20dp"
            android:paddingRight="10dp"
            android:singleLine="true"
            android:textColor="#ff444444"
            android:textColorHint="#ffcccccc"
            android:textSize="16sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/id_et_pwd_register"
            android:layout_marginTop="20dp"
            android:orientation="horizontal"
            android:paddingLeft="10dp"
            android:paddingRight="10dp" >

            <Button
                android:id="@+id/id_btn_ok"
                android:layout_width="0dp"
                android:layout_height="48dp"
                android:layout_weight="1.0"
                android:background="@drawable/btn_selector"
                android:text="确定"
                android:textColor="#ffffff"
                android:textSize="18sp" />

            <Button
                android:id="@+id/id_btn_cancel"
                android:layout_width="0dp"
                android:layout_height="48dp"
                android:layout_marginLeft="20dp"
                android:layout_weight="1.0"
                android:background="@drawable/btn_selector"
                android:text="取消"
                android:textColor="#ffffff"
                android:textSize="18sp" />
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>


下面是res/dawable/btn_selector.xml 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_focused="true" android:drawable="@drawable/btn_activity"/>
    <item android:state_pressed="true" android:drawable="@drawable/btn_activity"/>
    <item android:state_enabled="false" android:drawable="@drawable/btn_activity"/>
    <item android:drawable="@drawable/btn_default"/><!-- 默认 -->
</selector>


下面是res/dawable/edit_selector.xml 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_focused="true" android:drawable="@drawable/edit_activity"/>
    <item android:state_pressed="true" android:drawable="@drawable/edit_activity"/>
    <item android:state_enabled="false" android:drawable="@drawable/edit_activity"/>
    <item android:drawable="@drawable/edit_default"/><!-- 默认 -->
</selector>

添加相应的权限:

<!-- Bmob SDK权限 -->  
  <uses-permission android:name="android.permission.INTERNET" />  
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  <uses-permission android:name="android.permission.READ_PHONE_STATE" />  
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
  <uses-permission android:name="android.permission.READ_LOGS" />  


下面是LoginActivity.java文件:

public class LoginActivity extends Activity implements OnClickListener{
	private EditText et_account;
	private EditText et_password;
	private CheckBox check;
	private Button login;
	private Button register;
	private String account,password;
	
	private SharedPreferences pref;
	private SharedPreferences.Editor editor;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		// 初始化 Bmob SDK
		Bmob.initialize(this, "14fcb34593937578a18862a1b33f29a1");  
		initViews();
	}

	/**
	 * 初始化控件
	 */
	private void initViews() {
		et_account=(EditText) findViewById(R.id.id_et_account);
		et_password=(EditText) findViewById(R.id.id_et_pwd);
		check=(CheckBox) findViewById(R.id.id_checkBox);
		login=(Button) findViewById(R.id.id_login);
		register=(Button) findViewById(R.id.id_register);
		login.setOnClickListener(this);
		register.setOnClickListener(this);
		
		pref=getSharedPreferences("loginPassword", 0);
		editor=pref.edit();
		
		//取出数据
		String name=pref.getString("userName", "");
		String psw=pref.getString("password", "");
		if(name.equals("")){
			check.setChecked(false);
		}else{
			check.setChecked(true);
			et_account.setText(name);
			et_password.setText(psw);
		}
	}

	/**
	 *按钮响应事件 
	 */
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.id_login://登录用户
			account=et_account.getText().toString().trim();
			password=et_password.getText().toString().trim();
			if(account.equals("")){
				toast("填写你的用户名");
				return;
			}
			if(password.equals("")){
				toast("填写你的密码");
				return;
			}
			
			BmobUser bu=new BmobUser();
			bu.setUsername(account);
			bu.setPassword(password);
			bu.login(this, new SaveListener() {
				public void onSuccess() {
					if(check.isChecked()){
						editor.putString("userName", account);
						editor.putString("password", password);
						editor.commit();
					}else{
						//editor.clear();
						editor.remove("userName");
						editor.remove("password");
						editor.commit();
					}
					toast("登录成功:");
				}
				
				public void onFailure(int code, String msg) {
					toast("登录失败:"+msg);
				}
			});
			break;
			
		case R.id.id_register://注册用户
			Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
			startActivity(intent);
			break;
		}
	}
	
	/**
	 * 显示提示
	 */
	public void toast(String msg){
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}
}


下面是RegisterActivity.java文件:

public class RegisterActivity extends Activity implements OnClickListener{
	private EditText et_account;
	private EditText et_password;
	private Button btn_ok;
	private Button btn_cancel;
	
	private String account,password;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		initView();
	}
	
	/**
	 * 初始化控件
	 */
	private void initView(){
		et_account=(EditText) findViewById(R.id.id_et_account_register);
		et_password=(EditText) findViewById(R.id.id_et_pwd_register);
		btn_ok=(Button) findViewById(R.id.id_btn_ok);
		btn_cancel=(Button) findViewById(R.id.id_btn_cancel);
		btn_ok.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);
	}

	/**
	 * 按钮响应事件
	 */
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.id_btn_ok:
			account=et_account.getText().toString().trim();
			password=et_password.getText().toString().trim();
			if(account.equals("")){
				toast("填写你的用户名");
				return;
			}
			if(password.equals("")){
				toast("填写你的密码");
				return;
			}
			
			BmobUser bu2=new BmobUser();
			bu2.setUsername(account);
			bu2.setPassword(password);
			bu2.signUp(this, new SaveListener() {
				public void onSuccess() {
					toast("注册成功:");
					Intent intent=new Intent(RegisterActivity.this,LoginActivity.class);
					startActivity(intent);
				}
				
				public void onFailure(int code, String msg) {
					toast("注册失败:"+msg);
				}
			});
			break;
			
		case R.id.id_btn_cancel:
			Intent intent=new Intent(RegisterActivity.this,LoginActivity.class);
			startActivity(intent);
			break;
		}
	}
	
	/**
	 * 显示提示
	 */
	public void toast(String msg){
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}
}



Take your time and enjoy it 要原码的、路过的、学习过的请留个言,顶个呗~~


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值