### 1、SharedPreferences類的介紹
對于軟件配置參數的保存,如果是window軟件通常我們會采用ini文件進行保存;如果是j2se應用,我們會采用properties屬性文件或者xml進行保存。如果是Android應用,我們最適合采用什么方式保存軟件配置參數呢?Android平臺給我們提供了一個SharedPreferences類,它是一個輕量級的存儲類,特別適合用于保存軟件配置參數。使用SharedPreferences保存數據,其背后是用xml文件存放數據,文件存放在 /data/data/<package name>/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](http://blog.csdn.net/songshimvp1/article/details/50300521)
- 前言
- Java內部類
- 從一個View向一個Activity跳轉
- Android 與 SQLite
- Android工程A依賴B,B依賴C
- Android重要控件概覽(上)
- Installation error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
- Android布局概覽
- 動態引用APK文件
- Android重要控件概覽(中)
- Android重要控件概覽(下)
- Gallery和ImageSwitcher
- Android之Toast
- Android之Dialog
- Android之Notification
- Android之Menu
- Android Menu中android:showAsAction屬性
- Android SharedPreferences存儲數據的使用方法
- Android手勢識別之GestureDetector
- 不同APP通過SharedPreferences傳遞數據(共享數據)
- 一個自定義的Topbar模板
- 關于Activity回收造成View選中不對應的問題
- Android之Fragment靜態加載