牛骨文教育服务平台(让学习变的简单)

1、SharedPreferences类的介绍

对于软件配置参数的保存,如果是window软件通常我们会采用ini文件进行保存;如果是j2se应用,我们会采用properties属性文件或者xml进行保存。如果是Android应用,我们最适合采用什么方式保存软件配置参数呢?Android平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在 /data/data//shared_prefs 目录下(下面会对实际案例进行截图证明)。SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对),SharedPreferences常用来存储一些轻量级的数据。

2、SharedPreferences类的说明及简单分析

(1)获取SharedPreferences的两种方式:
1 调用Context对象的getSharedPreferences()方法;
2 调用Activity对象的getPreferences()方法;
两种方式的区别:
调用Context对象的getSharedPreferences()方法获得的SharedPreferences对象可以被同一应用程序下的其他组件共享;
调用Activity对象的getPreferences()方法获得的SharedPreferences对象只能在该Activity中使用; 

(2)SharedPreferences的四种操作模式:
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容;
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件;
Context.MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;
Context.MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入;

(3)将数据保存至SharedPreferences:

SharedPreferences preferences = getSharedPreferences("user",Context.MODE_PRIVATE);
Editor editor=preferences.edit();
String name="xixi";
String age="22";
editor.putString("name", name);
editor.putString("age", age);
editor.commit();

(4)从SharedPreferences获取数据:

SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
String name=preferences.getString("name", "defaultname");
String age=preferences.getString("age", "0");

3、简单案例展示:

               findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SharedPreferences sharedPreferences=getSharedPreferences("user", Context.MODE_PRIVATE);    // 实例化SharedPreferences对象
				
				Editor editor=sharedPreferences.edit();     // 实例化SharedPreferences.Editor对象
				editor.putString("name", "张三");            // 用putString的方法保存数据 
				editor.putString("IP", "192.168.1.102");
				editor.putString("password", "123456");
				editor.commit();                            // 提交当前数据 
				
				Toast.makeText(MainActivity.this, "写入数据成功!", Toast.LENGTH_SHORT).show();
			}
		});
		
		findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 在读取SharedPreferences数据前要实例化出一个SharedPreferences对象 
				SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);  
				
				String nameStr=preferences.getString("name", "dafultName");  // 使用getString方法获得value,注意第2个参数是value的默认值
				String ipStr=preferences.getString("IP", "");    // getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
				String pwStr=preferences.getString("password", "");
				
				Toast.makeText(MainActivity.this, "用户信息:姓名:"+nameStr+",IP:"+ipStr+",密码:"+pwStr, Toast.LENGTH_LONG).show();
				
			}
		});

关于SharedPreferences背后是使用xml文件保存数据,getSharedPreferences(name,mode)方法的第一个参数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上。方法的第二个参数指定文件的操作模式,共有四种操作模式,这四种模式前面介绍使用文件方式保存数据时已经讲解过。如果希望SharedPreferences背后使用的xml文件能被其他应用读和写,可以指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。
数据文件图示:


4、关于“记住用户登录信息”的案例:

xml:

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="用户名:" />

        <EditText
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:hint="请输入登录名" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="IP地址:" />

        <EditText
            android:id="@+id/ip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:hint="请输入IP地址" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="密    码:" />

        <EditText
            android:id="@+id/password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:hint="请输入密码"
            android:inputType="textPassword" />
    </LinearLayout>

    <CheckBox
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="记住用户名" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="登录" />

        <Button
            android:id="@+id/cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="取消" />
    </LinearLayout>

</LinearLayout>

Main.java

public class MainActivity extends Activity implements OnClickListener {

	private EditText etName,etIP,etPw;
	private CheckBox checkBox;
	private Button btnLogin,btnCancel;
	
	SharedPreferences sharedPreferences;
	Editor editor;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		etName=(EditText) findViewById(R.id.name);
		etIP=(EditText) findViewById(R.id.ip);
		etPw=(EditText) findViewById(R.id.password);
		
		checkBox=(CheckBox) findViewById(R.id.check);
		
		btnLogin=(Button) findViewById(R.id.login);
		btnCancel=(Button) findViewById(R.id.cancel);
					
		btnLogin.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		
		sharedPreferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
		editor = sharedPreferences.edit();

		String getName = sharedPreferences.getString("name", "");         //此处是关于“记住登录信息”的操作
		String getIP=sharedPreferences.getString("IP", "");
		String getPassword=sharedPreferences.getString("password", "");
		if(getName==null){
			checkBox.setChecked(false);
		}
		else{
			checkBox.setChecked(true);
			etName.setText(getName);
		}
	}

	@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;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.login:
			
			String name = etName.getText().toString().trim();
			String IP = etIP.getText().toString().trim();
			String password=etPw.getText().toString().trim();
			
			if(name.equals("admin") /*&& IP.equals("192.168.1.102")*/ && password.equals("GO")){
				if(checkBox.isChecked()){
					
					editor.putString("name", name);      //只记住登录名
					//editor.putString("IP", IP);
					//editor.putString("password", password);
					editor.commit();
					Toast.makeText(MainActivity.this, "登录名已保存", Toast.LENGTH_SHORT).show();
				}
				else{
					editor.remove("name");      //如果没有勾选“记住登录信息”
					//editor.remove("IP");
					//editor.remove("password");
					editor.commit();
					Toast.makeText(MainActivity.this, "登录名未保存", Toast.LENGTH_SHORT).show();
				}
				Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
			}
						
			break;

		case R.id.cancel:
			
			break;
		}
	}

}

效果图:

登陆成功以后,返回退出,重新进入该应用程序,用户名已经存在!(勾掉“记住用户名”,则不会自动填写用户名一栏)

4、不同APP通过SharedPreferences传递数据(共享数据)

具体案例见:http://blog.csdn.net/songshimvp1/article/details/50300521