這是Android學(xué)習(xí)筆記的第14篇炕婶,之前關(guān)于界面方面的學(xué)習(xí)總結(jié)暫時告一段落。這篇主要詳細介紹Android開發(fā)過程中數(shù)據(jù)存儲的常見幾種方式莱预。
一柠掂、概述
二、Shared Preferences 簡單鍵值對
三依沮、Internal Storage 內(nèi)部存儲
四涯贞、External Storage 外部存儲
五、SQLite數(shù)據(jù)庫
六危喉、Network Connection 網(wǎng)絡(luò)存儲
七宋渔、總結(jié)
一、概述
在平常的應(yīng)用開發(fā)中辜限,數(shù)據(jù)存儲應(yīng)該是我們經(jīng)常要接觸的內(nèi)容皇拣,同時也是相當重要的部分。例如薄嫡,要開發(fā)一個課程表的App氧急,如果用戶將自己的課程數(shù)據(jù)輸入,但是下次登錄時卻看不到之前的數(shù)據(jù)毫深,那這樣的App還有價值嗎吩坝,我們需要采取某種方式把數(shù)據(jù)存儲下來。Android為我們的數(shù)據(jù)存儲提供了很多選擇哑蔫,根據(jù)不同的存儲需要钉寝,可以采取不同的方式。
總的來說闸迷,數(shù)據(jù)存儲有兩種類別嵌纲,一種是存儲在本地,另一種是通過網(wǎng)絡(luò)把數(shù)據(jù)存儲在服務(wù)器端腥沽。本文主要介紹數(shù)據(jù)在本地存儲的4種基本方式逮走,包括Shared Preferences(簡單鍵值對存儲),Internal Storage (內(nèi)部存儲)巡球,External Storage (外部存儲)言沐,SQLite數(shù)據(jù)庫。
二酣栈、Shared Preferences 簡單鍵值對
1险胰、概述
Shared Preferences,直譯就是共用的配置信息矿筝,它的使用很簡單起便,主要是采用鍵值對的形式來保存應(yīng)用的一些常用配置等少量的數(shù)據(jù),且這些數(shù)據(jù)的格式非常簡單。例如榆综,用戶登錄時提供一個選擇按鈕妙痹,詢問是否記住密碼,這時就可以使用這種方式鼻疮。
2怯伊、例子
Shared Preferences平時在使用過程中比較簡單,經(jīng)常用到的有兩個類接口判沟,SharedPreferences和SharedPreferences.Editor耿芹。其中,后面的SharedPreferences.Editor主要是用于修改數(shù)據(jù)挪哄。下面以一個例子來講下它的用法吧秕。
1、下圖是個用戶登錄界面迹炼,輸入用戶名和密碼后登錄前可以選擇是否記住密碼砸彬,如果記住了,那么下次登錄的時候EditText里就直接顯示上次的用戶名和密碼斯入。
2砂碉、布局文件layout_preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="8dp">
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="用戶名">
<requestFocus />
</EditText>
<EditText
android:id="@+id/et_userpasswd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="密碼" />
<CheckBox
android:id="@+id/cb_keep"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="記住密碼" />
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:text="登錄" />
</LinearLayout>
3、Activity里的代碼SharedPreActivity 咱扣。
public class SharedPreActivity extends Activity {
SharedPreferences sp;
SharedPreferences.Editor spEditor;
private static final String FILE_USER = "FILE_USER_LO";
private static final String KEY_KEEP = "keeppswd";
private static final String KEY_USERNAME = "username";
private static final String KEY_USERPASSWD = "userpswd";
private EditText etUserName, etUserPasswd;
private Button btnLogin;
private CheckBox cbKeep;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_preferences);
initView();
initData();
}
private void initView() {
etUserName = (EditText) findViewById(R.id.et_username);
etUserPasswd = (EditText) findViewById(R.id.et_userpasswd);
cbKeep = (CheckBox) findViewById(R.id.cb_keep);
btnLogin = (Button) findViewById(R.id.btn_login);
}
//初始化數(shù)據(jù)
private void initData() {
sp = getSharedPreferences(FILE_USER, Context.MODE_PRIVATE);
//獲取之前是否點擊了保存密碼
cbKeep.setChecked(sp.getBoolean(KEY_KEEP, false));
//如果點擊了就獲取密碼
if (cbKeep.isChecked()) {
etUserName.setText(sp.getString(KEY_USERNAME, ""));
etUserPasswd.setText(sp.getString(KEY_USERPASSWD, ""));
}
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String userName = etUserName.getText().toString().trim();
String userPasswd = etUserPasswd.getText().toString().trim();
if (cbKeep.isChecked()) {
funDataSave(userName, userPasswd, 1);
} else {
funDataSave(userName, userPasswd, 0);
}
}
});
}
private void funDataSave(String username, String userpassword, int type) {
spEditor = sp.edit();
if (type == 0) {
spEditor.putBoolean(KEY_KEEP, false);
spEditor.putString(KEY_USERNAME, "");
spEditor.putString(KEY_USERPASSWD, "");
} else {
spEditor.putBoolean(KEY_KEEP, true);
spEditor.putString(KEY_USERNAME, username);
spEditor.putString(KEY_USERPASSWD, userpassword);
}
spEditor.apply();
}
}
3绽淘、用法解析
- Shared Preferences使用過程中,接口SharedPreferences通過getSharedPreferences(String name, int mode)方法來實例化闹伪,其中name是配置文件名,mode是配置文件操作模式壮池。我們這里傳入Context.MODE_PRIVATE偏瓤,表示該文件是私有數(shù)據(jù),只能被應(yīng)用本身訪問,在該模式下,寫入的內(nèi)容會覆蓋原文件的內(nèi)容。操作模式還有MODE_WORLD_READABLE椰憋,表示當前文件可以被其他應(yīng)用讀取厅克。
MODE_WORLD_WRITEABLE,表示當前文件可以被其他應(yīng)用寫入 - Shared Preferences允許我們存儲的數(shù)據(jù)主要有Boolean橙依、String证舟、Int、Float窗骑、Long等幾種女责,如果要對數(shù)據(jù)進行操作,通過SharedPreferences.edit()實例化接口SharedPreferences.Editor创译,之后通過putFloat(String key, float value)等方法可以將指定鍵名的數(shù)據(jù)存儲到配置文件里抵知,通過getFloat(String key, float defValue)等可以獲取到指定鍵名的數(shù)據(jù)。
- 對數(shù)據(jù)進行操作,必須要提交才能生效刷喜,可以選擇commit()或者apply()残制,官方推薦采用apply(),因為這種方法是異步進行的掖疮。
三初茶、Internal Storage 內(nèi)部存儲
1、概述
Internal Storage浊闪,內(nèi)部存儲恼布,主要是將數(shù)據(jù)文件保存到設(shè)備的內(nèi)部存儲中。
2规揪、用法與解析
- 將數(shù)據(jù)寫入到指定文件
/**
* 寫入數(shù)據(jù)到內(nèi)部存儲
*
* @param wData 數(shù)據(jù)
* @param filename 寫入到的文件
*/
private void funInternalWrite(String wData, String filename) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(wData.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- 讀取指定文件的內(nèi)容
private String funInternalRead(String filename) {
String rData = "";
try {
FileInputStream fis = openFileInput(filename);
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
rData = new String(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return rData;
}
- 其它有用的方法
getFilesDir() 得到文件的絕對路徑
getDir() 在內(nèi)部存儲上創(chuàng)建目錄桥氏,如果已經(jīng)存在就打開。
deleteFile() 刪除指定文件
fileList() 返回應(yīng)用存儲的文件列表
四猛铅、External Storage 外部存儲
1字支、概述
每個Android設(shè)備都支持一個共享的外部存儲,可以允許你存儲文件奸忽。它可能是一個可拆卸的SD卡堕伪,也可能是不能拆卸的。
2栗菜、用法與解析
- 添加權(quán)限
- 檢查外部存儲是否可用
- 外部存儲操作
- 添加權(quán)限
這里需要注意欠雌, WRITE_EXTERNAL_STORAGE其實包括了讀寫兩個權(quán)限,如果只需要讀可以只添加讀權(quán)限疙筹。
2富俄、檢查外部存儲是否可用
private static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
3、數(shù)據(jù)寫入外部存儲指定文件而咆。
public static void funExternalWrite(String data, String filename) {
FileOutputStream fos = null;
File file = new File(Environment.getExternalStorageDirectory(), filename);
if (isExternalStorageWritable()) {
try {
fos = new FileOutputStream(file, true);
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
4霍比、讀取外部存儲指定文件
public static String funExternalRead(String filename) {
FileInputStream fileInputStream = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File file = new File(Environment.getExternalStorageDirectory(), filename);
if (isExternalStorageWritable()) {
try {
fileInputStream = new FileInputStream(file);
int len = 0;
byte[] data = new byte[1024];
while ((len = fileInputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return new String(byteArrayOutputStream.toByteArray());
}
五、SQLite數(shù)據(jù)庫
Android provides full support for SQLite databases. Any databases you create will be accessible by name to any class in the application, but not outside the application.
Android完全支持SQLite數(shù)據(jù)庫暴备,應(yīng)用中的任何數(shù)據(jù)庫都可以通過名稱來訪問悠瞬,但是別的應(yīng)用不可以,當然應(yīng)用間的數(shù)據(jù)共享可以用Content Provider來實現(xiàn)涯捻。
SQLite數(shù)據(jù)庫使用的一般步驟有:
-
新建一個繼承自SQLiteOpenHelper 的子類浅妆,在其中完成數(shù)據(jù)庫的初始化操作,包括創(chuàng)建表等等障癌。重寫onCreate方法在里面完成數(shù)據(jù)表的創(chuàng)建凌外,onUpdate是數(shù)據(jù)庫更新時調(diào)用的。下面這張圖是個簡單的例子混弥。
SQLiteOpenHelper 類 -
對數(shù)據(jù)庫進行操作前一般先獲取一個SQLiteDatabase 對象趴乡,利用它我們可以完成對數(shù)據(jù)庫表的操作对省,比如增刪改查等等。下面這張圖是一個對數(shù)據(jù)表執(zhí)行刪除操作的函數(shù)晾捏,應(yīng)該比較清楚蒿涎。
數(shù)據(jù)庫表刪除指定記錄
SQLite數(shù)據(jù)庫其實很強大,熟悉常見的sql語句惦辛,可以很簡單地完成對數(shù)據(jù)庫表的操作劳秋。
六、Network Connection 網(wǎng)絡(luò)存儲
網(wǎng)絡(luò)存儲主要是把數(shù)據(jù)存儲到服務(wù)器端胖齐,這部分內(nèi)容我會在以后的博客中繼續(xù)更新玻淑,歡迎大家繼續(xù)關(guān)注。
七呀伙、總結(jié)
應(yīng)用中數(shù)據(jù)存儲的常見幾種方式就是以上這些补履,內(nèi)容提供者Content Provider的使用過程中通常會用到SQLite數(shù)據(jù)庫,這個部分的內(nèi)容大家可以看我之前的第3篇文章剿另。最后箫锤,關(guān)于數(shù)據(jù)存儲方式部分的使用,稍后會貼出源碼鏈接雨女。