`
毛驴追飞机
  • 浏览: 16305 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

使用SharedPreferences实现登录记住密码

阅读更多

SharedPreferences

 SharedPreferences是一种轻型的数据存储方式,本质是基于xml文件存储Key-value的键值对数据,一般用来存储一些简单配置信息。其存储位置在/data/data/<应用包名>/shared_prefs目录下。

实现SharedPreferences存储的步骤如下:

 

1、创建SharedPreferences对象,有两种方式:

 

(1)调用Context对象的getSharedPreferences()方法,通过这种方式获得的SharedPreferences对象可以被统一应用程序下的其他组建共享,也可以指定存储的文件名和操作模式。

SharedPreferences preferences=getSharedPreferences("demo",Context.MODE_PRIVATE);

 

(2)调用Activity对象的getPreferences()方法,这种方式获得的SharedPreferences对象只能在该Activity中使用,只需指定操作模式即可。

 

SharedPreferences preferences=getPreferences(MODE_WORLD_WRITEABLE);

 

 

SharedPreferences有四种操作模式:

Context.MODE_PRIVATE:为默认操作模式,代表文件是私有数据,只能被应用本身访问。在该模式下写入的内容会覆盖源文件的内容。

  Context.MODE_APPEND:检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
  Context.MODE_WORLD_READABLE:表示当前文件可以被其他应用读取。
  Context.MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。

2、利用edit()方法获取Editor对象。

3、通过Editor对象存储key-value键值对象数据。

4、通过commit()方法提交数据。

 

下面用一个简单的登录案例,来实现SharedPreferences的存储方式。

首先创建布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:background="@drawable/bg"  
    android:orientation="vertical" >  
  
    <RelativeLayout  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content" >  
   
  
        <TextView  
            android:id="@+id/tv_user_name"  
            android:layout_width="wrap_content"  
            android:layout_height="35dip"  
            android:layout_marginLeft="12dip"  
            android:layout_marginTop="10dip"  
            android:gravity="bottom"  
            android:text="用户名:"  
            android:textColor="#000000"  
            android:textSize="18sp" />  
  
        <EditText  
            android:id="@+id/et_user_name"  
            android:layout_width="fill_parent"  
            android:layout_height="40dip"  
            android:layout_below="@id/tv_user_name"  
            android:layout_marginLeft="12dip"  
            android:layout_marginRight="10dip" />  
  
        <TextView  
            android:id="@+id/tv_password"  
            android:layout_width="wrap_content"  
            android:layout_height="35dip"  
            android:layout_below="@id/et_user_name"  
            android:layout_marginLeft="12dip"  
            android:layout_marginTop="10dip"  
            android:gravity="bottom"  
            android:text="密码:"  
            android:textColor="#000000"  
            android:textSize="18sp" />  
  
        <EditText  
            android:id="@+id/et_password"  
            android:layout_width="fill_parent"  
            android:layout_height="40dip"  
            android:layout_below="@id/tv_password"  
            android:layout_marginLeft="12dip"  
            android:layout_marginRight="10dip"  
            android:maxLines="200"  
            android:password="true"  
            android:scrollHorizontally="true" />  
  
        <CheckBox  
            android:id="@+id/cb_password"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_below="@id/et_password"  
            android:layout_marginLeft="12dip"  
            android:text="记住密码"  
            android:textColor="#000000" />  
  
        <Button  
            android:id="@+id/btn_login"  
            android:layout_width="80dip"  
            android:layout_height="40dip"  
            android:layout_below="@id/cb_password"  
            android:layout_alignParentRight="true"  
            android:layout_alignTop="@id/cb_password"  
            android:layout_marginRight="10dip"  
            android:gravity="center"  
            android:text="登录"  
            android:textColor="#000000"  
            android:textSize="18sp"/>  
  
          
    </RelativeLayout>  
      
      
  
</LinearLayout>

 创建Activity

package com.example.logindemo;

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

/**
 * 
 * @author hx
 * @version create 2014-11-24 19:30
 *
 */
public class MainActivity extends Activity {

	private EditText userName;
	private EditText password;
	private CheckBox rem_password;
	private Button bt_login;
	private String userNameValue;
	private String passwordValue;
	private SharedPreferences sp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//创建对象,userInfo表示信息存储的文件名,安卓会默认添加.xml后缀名
		sp = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		userName = (EditText) findViewById(R.id.et_user_name);
		password = (EditText) findViewById(R.id.et_password);
		rem_password = (CheckBox) findViewById(R.id.cb_password);
		bt_login = (Button) findViewById(R.id.btn_login);
		
		//判断记住密码状态
		if(sp.getBoolean("ISCHECK", false)){
			userName.setText(sp.getString("USER_NAME", ""));
			password.setText(sp.getString("PASSWORD", ""));
		}
		
		//添加记录密码复选框更改事件
		rem_password.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				// TODO Auto-generated method stub
				if(rem_password.isChecked()){
					Editor editor = sp.edit();
					editor.putBoolean("ISCHECK", true);
					editor.commit();
				}else{
					Editor editor = sp.edit();
					editor.putBoolean("ISCHECK", false);
					editor.commit();
				}
			}
			});
		
		//添加登录按钮事件
		bt_login.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				userNameValue = userName.getText().toString();
				passwordValue = password.getText().toString();
				
				if(userNameValue.equals("admin") && passwordValue.equals("123456")){
					Toast.makeText(MainActivity.this,"登录成功", Toast.LENGTH_SHORT).show();  
					//记录密码操作
					if(rem_password.isChecked()){
						Editor editor = sp.edit();
						editor.putString("USER_NAME", userNameValue);
						editor.putString("PASSWORD", passwordValue);
						editor.commit();
					}
				}else{
					Toast.makeText(MainActivity.this,"登录失败", Toast.LENGTH_SHORT).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;
	}

}

 运行完,通过eclipse的File Explorer查看文件。如果遇到无法查看的情况,注意观察该文件夹的权限。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics