Android學(xué)習(xí)筆記14 數(shù)據(jù)存儲全攻略

這是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绽淘、用法解析

  1. 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)用寫入
  2. 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ù)。
  3. 對數(shù)據(jù)進行操作,必須要提交才能生效刷喜,可以選擇commit()或者apply()残制,官方推薦采用apply(),因為這種方法是異步進行的掖疮。

三初茶、Internal Storage 內(nèi)部存儲

1、概述

Internal Storage浊闪,內(nèi)部存儲恼布,主要是將數(shù)據(jù)文件保存到設(shè)備的內(nèi)部存儲中。

2规揪、用法與解析

  1. 將數(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();
        }
    }
  1. 讀取指定文件的內(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;
    }
  1. 其它有用的方法
    getFilesDir() 得到文件的絕對路徑
    getDir() 在內(nèi)部存儲上創(chuàng)建目錄桥氏,如果已經(jīng)存在就打開。
    deleteFile() 刪除指定文件
    fileList() 返回應(yīng)用存儲的文件列表

四猛铅、External Storage 外部存儲

1字支、概述

每個Android設(shè)備都支持一個共享的外部存儲,可以允許你存儲文件奸忽。它可能是一個可拆卸的SD卡堕伪,也可能是不能拆卸的。

2栗菜、用法與解析

  • 添加權(quán)限
  • 檢查外部存儲是否可用
  • 外部存儲操作
  1. 添加權(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ù)庫使用的一般步驟有:

  1. 新建一個繼承自SQLiteOpenHelper 的子類浅妆,在其中完成數(shù)據(jù)庫的初始化操作,包括創(chuàng)建表等等障癌。重寫onCreate方法在里面完成數(shù)據(jù)表的創(chuàng)建凌外,onUpdate是數(shù)據(jù)庫更新時調(diào)用的。下面這張圖是個簡單的例子混弥。


    SQLiteOpenHelper 類
  2. 對數(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ù)存儲方式部分的使用,稍后會貼出源碼鏈接雨女。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末谚攒,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子氛堕,更是在濱河造成了極大的恐慌馏臭,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件讼稚,死亡現(xiàn)場離奇詭異括儒,居然都是意外死亡,警方通過查閱死者的電腦和手機锐想,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進店門塑崖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人痛倚,你說我怎么就攤上這事±教桑” “怎么了蝉稳?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長掘鄙。 經(jīng)常有香客問我耘戚,道長,這世上最難降的妖魔是什么操漠? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任收津,我火速辦了婚禮饿这,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘撞秋。我一直安慰自己长捧,他們只是感情好,可當我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布吻贿。 她就那樣靜靜地躺著串结,像睡著了一般。 火紅的嫁衣襯著肌膚如雪舅列。 梳的紋絲不亂的頭發(fā)上肌割,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天,我揣著相機與錄音帐要,去河邊找鬼把敞。 笑死,一個胖子當著我的面吹牛榨惠,可吹牛的內(nèi)容都是我干的奋早。 我是一名探鬼主播,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼冒冬,長吁一口氣:“原來是場噩夢啊……” “哼伸蚯!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起简烤,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤剂邮,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后横侦,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體挥萌,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年枉侧,在試婚紗的時候發(fā)現(xiàn)自己被綠了引瀑。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡榨馁,死狀恐怖憨栽,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情翼虫,我是刑警寧澤屑柔,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站珍剑,受9級特大地震影響掸宛,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜招拙,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一唧瘾、第九天 我趴在偏房一處隱蔽的房頂上張望措译。 院中可真熱鬧,春花似錦饰序、人聲如沸领虹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽掠械。三九已至,卻和暖如春注祖,著一層夾襖步出監(jiān)牢的瞬間猾蒂,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工是晨, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留肚菠,地道東北人。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓罩缴,卻偏偏與公主長得像蚊逢,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子箫章,可洞房花燭夜當晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容