Android自学之SharedPreferences存储实现记录密码功能

不同于文件的存储方式,SharedPreferences是使用键值对的方式来存储数据的。也就是说当保存一条数据的时候,需要给这条数据提供一个对应的键,这样在读取数据的时候就可以通过这个键把相应的值取出来。而且SharedPreferences还支持多种不同的数据类型存储,如果存储的数据类型是整型,那么读取出来的数据也是整型的,存储的数据是一个字符串,读取出来的数据仍然是字符串。


要想使用SharedPreferences来存储数据, 首先需要获取到SharedPreferences对象。 Android中主要提供了三种方法用于得到SharedPreferences对象。
1. Context 类中的 getSharedPreferences()方法
此方法接收两个参数,第一个参数用于指定 SharedPreferences文件的名称,如果指定的文件不存在则会创建一个,SharedPreferences 文件都是存放在/data/data/<packagename>/shared_prefs/目录下的。第二个参数用于指定操作模式,主要有两种模式可以选择,MODE_PRIVATE和 MODE_MULTI_PROCESS。MODE_PRIVATE仍然是默认的操作模式,和直接传入 0 效果是相同的,表示只有当前的应用程序才可以对这个SharedPreferences文件进行读写。 MODE_MULTI_PROCESS则一般是用于会有多个进程中对同一个 SharedPreferences文件进行读写的情况。类似地,MODE_WORLD_READABLE
和 MODE_WORLD_WRITEABLE 这两种模式已在 Android 4.2版本中被废弃。
2. Activity类中的 getPreferences()方法
这个方法和 Context 中的 getSharedPreferences()方法很相似,不过它只接收一个操
作模式参数,因为使用这个方法时会自动将当前活动的类名作为 SharedPreferences的文
件名。
3. PreferenceManager类中的 getDefaultSharedPreferences()方法
这是一个静态方法,它接收一个 Context 参数,并自动使用当前应用程序的包名作为前缀来命名 SharedPreferences文件。
得到了 SharedPreferences对象之后, 就可以开始向 SharedPreferences文件中存储数据了,主要可以分为三步实现。
1. 调用 SharedPreferences对象的 edit()方法来获取一个 SharedPreferences.Editor对象。
2. 向 SharedPreferences.Editor 对象中添加数据,比如添加一个布尔型数据就使用putBoolean方法,添加一个字符串则使用 putString()方法,以此类推。
3. 调用 commit()方法将添加的数据提交,从而完成数据存储操作。

下边就开始贴代码吧:

xml代码:

<span style="font-size:14px;"><TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1" >

	<TableRow>
		<TextView
		android:layout_height="wrap_content"
		android:text="Account:" />
		<EditText
		android:id="@+id/account"
		android:layout_height="wrap_content"
		android:hint="Input your account" />
	</TableRow>
	
	<TableRow>
		<TextView
		android:layout_height="wrap_content"
		android:text="Password:" />
		<EditText
		android:id="@+id/password"
		android:layout_height="wrap_content"
		android:inputType="textPassword" />
		
	</TableRow>
	
	<LinearLayout>	
		<CheckBox 
        android:id="@+id/remember_pass"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Remember Password"/>
	</LinearLayout>
	
	<TableRow>
		<Button
		android:id="@+id/login"
		android:layout_height="wrap_content"
		android:layout_span="2"
		android:text="Login" />
	</TableRow>
  
    
</TableLayout></span>

java代码:

<span style="font-size:14px;">package com.example.broadcastbestpractice;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
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 MainActivity extends Activity {

	private SharedPreferences pref;				//SharedPreferences是使用键值对来存储数据的
	private SharedPreferences.Editor editor;
	
	private EditText accountEdit;			//用户名
	private EditText passwordEdit;			//密码
	private Button login;					//登录按钮
	
	private CheckBox rememberPass;			//checkbox 用来判断是否记录密码
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		pref = PreferenceManager.getDefaultSharedPreferences(this);
		
		accountEdit = (EditText) findViewById(R.id.account);
		passwordEdit = (EditText) findViewById(R.id.password);
		rememberPass = (CheckBox) findViewById(R.id.remember_pass);			//checkbox
		login = (Button) findViewById(R.id.login);
		
//		key            获取的preference的名称
//		defValue 当此preference不存在时返回的默认值
//		如果preference存在,则返回preference的值,否则返回defValue。如果使用此名称的preference不是一个boolean类型,则抛出ClassCastException。
//		异常:ClassCastException 		
		boolean isRemember = pref.getBoolean("remember_password", false);		//如果不存在则返回false
		
		if (isRemember) {
			//将帐号和密码都设置到文本框中
			String account = pref.getString("account", "");
			String password = pref.getString("password", "");
			
			accountEdit.setText(account);
			passwordEdit.setText(password);
			
			rememberPass.setChecked(true);
		}
		
		login.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String account = accountEdit.getText().toString();
				String password = passwordEdit.getText().toString();
				
				if (account.equals("admin") && password.equals("1234")) {
					editor = pref.edit();				//把SharedPreferences保存的值赋出来
					
					if (rememberPass.isChecked()) {
						editor.putBoolean("remember_password", true);
						editor.putString("account", account);
						editor.putString("password", password);
					}
					else
					{
						editor.clear();
					}
					
					editor.commit();
					
					Intent intent = new Intent(MainActivity.this, FirstActivity.class);<span>	</span>//调用另一个活动
					startActivity(intent);
					finish();
				}
				else
				{
					Toast.makeText(MainActivity.this, "account or password is invalid.", Toast.LENGTH_LONG).show();
				}
				
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
</span>

到这里就基本OK了。。。


具体SharedPreferences类的使用方法贴了几个网上查找的连接:

http://blog.csdn.net/xiaanming/article/details/9339515

http://blog.csdn.net/bear_huangzhen/article/details/46551433

刚自学android不久,有补足之初请指正。。。谢谢

















  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zheguangqi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值