Android數(shù)據(jù)持久化之Preferences機(jī)制詳解
本文實(shí)例講述了Android數(shù)據(jù)持久化之Preferences機(jī)制。分享給大家供大家參考,具體如下:
在Android中,實(shí)現(xiàn)數(shù)據(jù)持久化有五種方式:Preferences,文件File,I/O操作、SQLite數(shù)據(jù)庫(kù),ContentProvider組件。
下面逐個(gè)做一簡(jiǎn)單的介紹:
一、Preferences的介紹:
Preferences是一種輕量級(jí)的數(shù)據(jù)存儲(chǔ)機(jī)制,他將一些簡(jiǎn)單的數(shù)據(jù)類(lèi)型的數(shù)據(jù),包括boolean類(lèi)型,int類(lèi)型,float類(lèi)型,long類(lèi)型以及String類(lèi)型的數(shù)據(jù),以鍵值對(duì)的形式存儲(chǔ)在應(yīng)用程序的私有Preferences目錄(/data/data/<包名>/shared_prefs/)中,這種Preferences機(jī)制廣泛應(yīng)用于存儲(chǔ)應(yīng)用程序中的配置信息。
如下是Preferences的一個(gè)簡(jiǎn)單代碼:
這個(gè)代碼是創(chuàng)建不同權(quán)限的數(shù)據(jù)對(duì)象:
package com.example.data_sharedpreferences;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView text;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 寫(xiě)入數(shù)據(jù)
writeData();
text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button0);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 讀取數(shù)據(jù)
readData();
}
});
}
/**
* 寫(xiě)入數(shù)據(jù)
*/
public void writeData() {
// 設(shè)置權(quán)限為私有MODE_PRIVATE
SharedPreferences sp_p = this.getSharedPreferences("ct_sp_private",
Context.MODE_PRIVATE);
// 通過(guò)SharedPreferences對(duì)象的編輯器對(duì)象Editor來(lái)實(shí)現(xiàn)存入數(shù)據(jù)
SharedPreferences.Editor editor = sp_p.edit();
// 通過(guò)該編輯器函數(shù)設(shè)置鍵值
editor.putString("username", "marry_private");
// 提交數(shù)據(jù),并將數(shù)據(jù)寫(xiě)入xml文件中
editor.commit();
// 設(shè)置為只讀
SharedPreferences sp_or = this.getSharedPreferences("ct_sp_private",
Context.MODE_WORLD_READABLE);
sp_or.edit().putString("username", "marry_only_read").commit();
// 設(shè)置為只寫(xiě)
SharedPreferences sp_ow = this.getSharedPreferences("ct_sp_private",
Context.MODE_WORLD_WRITEABLE);
sp_ow.edit().putString("username", "marry_only_write").commit();
// 設(shè)置為可讀可寫(xiě)
SharedPreferences sp_x = this.getSharedPreferences("ct_sp_private",
Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
sp_x.edit().putString("username", "marry_write_read").commit();
}
/**
* 讀取數(shù)據(jù)
* 通過(guò)SharedPreferences對(duì)象的鍵key可以獲取到對(duì)應(yīng)key的鍵值value。對(duì)于不同類(lèi)型的鍵值有不同的函數(shù):getBoolean
* ,getInt,getFloat,getLong.
*/
public void readData() {
// TODO Auto-generated method stub
text.setText("private_username:"
+ this.getSharedPreferences("ct_cp_private", 0).getString(
"username", "marry_private")
+ "\r\n"
+ "read_username:"
+ this.getSharedPreferences("ct_cp_private", 0).getString(
"username", "marry_only_read")
+ "\r\n"
+ "write_username:"
+ this.getSharedPreferences("ct_cp_private", 0).getString(
"username", "marry_only_write")
+ "\r\n"
+ "write_read_username:"
+ this.getSharedPreferences("ct_cp_private", 0).getString(
"username", "marry_write_read") + "\r\n");
}
@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;
}
}
下面這個(gè)代碼則是實(shí)現(xiàn)在另外一個(gè)應(yīng)用中訪問(wèn)上一個(gè)應(yīng)用,并讀取上面應(yīng)用的數(shù)據(jù):
package com.example.data_sharedpreferences2;
import com.example.data_sharedpreferences2.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* 該程序的功能是訪問(wèn)data_sharedpreferences應(yīng)用 Sharedpreferences訪問(wèn)另一個(gè)應(yīng)用的條件:
* 1、被訪問(wèn)的應(yīng)用權(quán)限為可讀或者可寫(xiě) 2、必須要知道被訪問(wèn)應(yīng)用的包名
*
* @author marry
*
*/
public class MainActivity extends Activity {
private TextView text;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button0);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 訪問(wèn)應(yīng)用1,并讀取應(yīng)用1的數(shù)據(jù)
try {
// 獲得要訪問(wèn)應(yīng)用的context
Context ortherContext = createPackageContext(
"com.example.data_sharedpreferences", 0);
// 通過(guò)ortherContext.getSharedPreferences打開(kāi)應(yīng)用1的文件
text.setText("private_username:"
+ ortherContext.getSharedPreferences(
"ct_cp_private", 0).getString("username",
"marry_private")
+ "\r\n"
+ "read_username:"
+ ortherContext.getSharedPreferences(
"ct_cp_private", 0).getString("username",
"marry_only_read")
+ "\r\n"
+ "write_username:"
+ ortherContext.getSharedPreferences(
"ct_cp_private", 0).getString("username",
"marry_only_write")
+ "\r\n"
+ "write_read_username:"
+ ortherContext.getSharedPreferences(
"ct_cp_private", 0).getString("username",
"marry_write_read") + "\r\n");
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@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;
}
}
使用Preferences時(shí)有以下需要注意的地方:
1、 通過(guò)Context.getSharedPreferences(String fileName,int mode)方法,可以打開(kāi)一個(gè)xml文件,文件的位置在/data/data/package_name/shared_prefs/fileName.xml,如果不存在,則會(huì)自動(dòng)創(chuàng)建。可以對(duì)該文件進(jìn)行讀寫(xiě)操作,在應(yīng)用內(nèi)的各組件之間共享數(shù)據(jù)。如果將mode設(shè)置為Context.MODE_WORLD_READ或者Context.MODE_WORLD_WRITE,則還可以被其他應(yīng)用訪問(wèn)到。不過(guò)這不是android推薦的方式,要實(shí)現(xiàn)跨應(yīng)用共享數(shù)據(jù),推薦的方式是用ContentProvider實(shí)現(xiàn)
2、 如果要訪問(wèn)另一個(gè)應(yīng)用創(chuàng)建的shared_prefs文件,需要滿(mǎn)足2個(gè)條件,首先另一個(gè)應(yīng)用要設(shè)置MODE_WORLD_READ或MODE_WORLD_WIRTE權(quán)限,并且要知道另一個(gè)應(yīng)用的package_name,然后就可以通過(guò)Context.createPackageContext()方法,就可以得到另一個(gè)應(yīng)用的context,然后context.getSharedPreferences()方法,就可以打開(kāi)shared_prefs文件了。不過(guò)這種方法并不推薦
3、 在罕見(jiàn)的情況下,如果既把shared_prefs的權(quán)限設(shè)置為MODE_PRIVATE,又希望某些其他的應(yīng)用可以訪問(wèn)到,那么可以在manifest文件中配置android:user_id(好像是這個(gè)屬性),讓多個(gè)應(yīng)用共享USER_ID。因?yàn)楸举|(zhì)上shared_prefs文件是采用linux的權(quán)限控制的,MODE_PRIVATE類(lèi)似于-rw-------,所以如果多個(gè)應(yīng)用使用了同一個(gè)USER_ID,自然都對(duì)這個(gè)文件有訪問(wèn)權(quán)限了
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Android數(shù)據(jù)庫(kù)操作技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android文件操作技巧匯總》、《Android編程開(kāi)發(fā)之SD卡操作方法匯總》、《Android開(kāi)發(fā)入門(mén)與進(jìn)階教程》、《Android資源操作技巧匯總》、《Android視圖View技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- Android startActivityForResult實(shí)例詳解
- Android在Fragment中實(shí)現(xiàn)監(jiān)聽(tīng)觸摸事件
- Android 使用FragmentTabhost代替Tabhost
- Android數(shù)據(jù)持久化之File機(jī)制分析
- Android 如何本地加載pdf文件
- Android利用FlexboxLayout輕松實(shí)現(xiàn)流動(dòng)布局
- android手機(jī)端與PC端使用adb forword通信
- Android 中SwipeRefreshLayout與ViewPager滑動(dòng)事件沖突解決方法
- Android 7.0行為變更 FileUriExposedException解決方法
相關(guān)文章
Android編程實(shí)現(xiàn)調(diào)用系統(tǒng)分享功能示例
這篇文章主要介紹了Android編程實(shí)現(xiàn)調(diào)用系統(tǒng)分享功能,結(jié)合實(shí)例形式分析了Android實(shí)現(xiàn)針對(duì)文字、圖片等元素分享功能的相關(guān)操作技巧,需要的朋友可以參考下2017-01-01
Android 權(quán)限(permission)整理
本文主要介紹Android 權(quán)限的整理,在開(kāi)發(fā)Android應(yīng)用的時(shí)候,根據(jù)需求的不同,會(huì)用到不同的權(quán)限,這里整理了很多,有需要的同學(xué)可以參考下2016-07-07
Android側(cè)邊欄滑動(dòng)切換的view效果
這篇文章主要介紹了Android側(cè)邊欄滑動(dòng)切換的view效果,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-03-03
Android開(kāi)發(fā)之TimePicker控件用法實(shí)例詳解
這篇文章主要介紹了Android開(kāi)發(fā)之TimePicker控件用法,結(jié)合實(shí)例形式詳細(xì)分析了Android項(xiàng)目的建立及TimePicker控件的具體使用技巧,需要的朋友可以參考下2016-02-02
Android自動(dòng)提示控件AutoCompleteTextView
這篇文章主要介紹了Android自動(dòng)提示控件AutoCompleteTextView的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12

