获取SharedPreferences的两种方式:
1 调用Context对象的getSharedPreferences()方法
2 调用Activity对象的getPreferences()方法
两种方式的区别:
调用Context对象的getSharedPreferences()方法获得的SharedPreferences对象可以被同一应用程序下的其他
组件共享.
调用Activity对象的getPreferences()方法获得的SharedPreferences对象只能在该Activity中使用.
SharedPreferences的四种操作模式:
Context.MODE_PRIVATE
Context.MODE_APPEND
Context.MODE_WORLD_READABLE
Context.MODE_WORLD_WRITEABLE
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件.
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件.
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取.
MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入.
将数据保存至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();
从SharedPreferences获取数据:
SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
String name=preferences.getString("name", "defaultname");
String age=preferences.getString("age", "0");
下面做一个类似记住密码功能的Demo,界面如下
代码示例:
布局文件activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/usernameEditText" android:hint="请输入用户名"/>
<EditText
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/passwordEditText" android:hint="请输入密码"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<CheckBox
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:id="@+id/remCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/rem_password" />
<Button
android:paddingRight="50dp"
android:paddingLeft="50dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:id="@+id/loginBt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login" android:textColor="#ec3c3c"/>
</RelativeLayout>
</LinearLayout>
package com.nii.preference;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity
{
/**
* 用户名
*/
private EditText usernameEditText;
/**
* 密码
*/
private EditText passwordEditText;
/**
* 是否记住密码
*/
private CheckBox remCheckbox;
/**
* 登录按钮
*/
private Button loginBt;
/**
* 上下文
*/
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
usernameEditText = (EditText) findViewById(R.id.usernameEditText);
passwordEditText = (EditText) findViewById(R.id.passwordEditText);
remCheckbox = (CheckBox) findViewById(R.id.remCheckbox);
loginBt = (Button) findViewById(R.id.loginBt);
loginBt.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
login();
}
});
//获取用户名密码
Map<String, String> map = getUserInfo();
if (map != null)
{
String username = map.get("username");
String password = map.get("password");
usernameEditText.setText(username);//设置用户名
passwordEditText.setText(password);
remCheckbox.setChecked(true);//设置复选框选中状态
}
}
private void login()
{
String username = usernameEditText.getText().toString().trim();
String password = passwordEditText.getText().toString().trim();
boolean isrem = remCheckbox.isChecked();
//d.判断用户名密码是否为空,不为空请求服务器(省略,默认请求成功)
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password))
{
Toast.makeText(mContext, "用户名密码不能为空", Toast.LENGTH_SHORT).show();
return;
}
//e.判断是否记住密码,如果记住,将用户名密码保存本地
if (isrem)
{
boolean result = saveUserInfo(username, password);
if (result)
{
Toast.makeText(mContext, "用户名密码保存成功", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(mContext, "用户名密码保存失败", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(mContext, "无需保存", Toast.LENGTH_SHORT).show();
}
}
/**
* 保存用户名和密码
*
* @param username username
* @param password password
* @return 结果 true 保存成功 | false 保存失败
*/
public boolean saveUserInfo(String username, String password)
{
try
{
SharedPreferences sharedPreferences = mContext.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
/**
* 获取用户名信息
*
* @return 信息
*/
public Map<String, String> getUserInfo()
{
try
{
//1.通过Context对象创建一个SharedPreference对象
SharedPreferences sharedPreferences = mContext.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
String password = sharedPreferences.getString("password", "");
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", username);
hashMap.put("password", password);
return hashMap;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
_