今天的筆記是要來講述關於Android中儲存資料的方法,SharedPreferences

基本上,在Android 中常見的儲存資料的方法有以下幾種

1. SharedPreferences: 利用Map陣列的方法儲存資料

2. ContentProvider: 可將此APP儲存的內容分享給其他APP使用(例如電話簿APP)

3. 儲存至手機內: 簡單來說就是存在SD卡或者手機內部儲存的方式

4. SQLite: 熟道不能再熟了吧?手機版資料庫 〓D

5. 網路(雲端)儲存: 就是連接網路來取得資料....前提是你要有資料庫可以用...

 

而今天要介紹的是SharedPreferences

看簡介..."Map陣列的方法存資料"??所以要用HashMap或Map嗎?(´・_・`)

噢不~並不需要,Android都幫你把套件寫好了XD

只要照著操作就可以囉(笑)

 

那麼,請問這個技術應用在哪裡呢?(對我而言這才是重點~)

其實,這個技術一直充斥在你身邊哦!

你想想麻,我們是不是在需要登入的APP中,很多APP都是只要登入過一次後接著就不會再叫你輸入帳號密碼登入呢?(銀行的APP除外....)

 

沒錯,就是這個技術!

以及有些APP都會有一些所謂的"偏好設定"

像是字體大小、黑色背景、帳號自動填入等,這些有部分都是用這個技術喔!

 

那麼,就來上功能吧

Gif_20200711152349566_by_gifguru

以及Github

https://github.com/thumbb13555/SharedpreferencesExample/tree/master

 


 

1. 簡介

今天要做的範例就是一個簡易儲存字串的範例

我會在第二的Activity中儲存字串,然後這個字串在被清除之前,這串字都不會被消滅

大體的形式就像這樣

截圖 2020-07-11 下午5.20.12

然後,來看一下關於SharedPreferences

官方文檔

->https://developer.android.com/reference/android/content/SharedPreferences

 

獲取SharedPreferences時,會使用在Activity類別中的getSharedPreferences方法

getSharedPreferences的使用,除了要決定儲存的名稱外,也要決定他的操作模式

操作模式有如下四種

1.  Context.MODE_PRIVATE ->指定其數據只能被本APP使用

2.Context.MODE_WORLD_READABLE ->指定該數據可被其他APP讀取,但是不能寫入

3. Context.MODE_WORLD_WRITEABLE ->該數據可以被其他APP讀寫

4. Context.MODE_APPEND ->這個模式會檢查這個儲存的文件是否存在,存在則自動增加內容,否則創立文件(文件可理解為資料表)

而因為Google致力於保護個資,故2、3 兩個已經在Android 4.2 版中被廢棄_(:3」∠)_

 

而要編輯資料時,並非使用方法SharedPreferences類別,而是使用一個叫做SharedPreferences.Editor方法

最後編輯完成資料後,才會推送至SharedPreferences

 


 

2. 畫介面與創立Activity

範例中有兩個Activity,大致就像這樣

截圖 2020-07-11 下午5.40.18

 

直接給兩個介面吧

 


 

MainActivity.java

截圖 2020-07-11 下午6.00.14

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintGuide_percent="0.6"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView_Display"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_Display"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顯示已存的資料"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toStartOf="@+id/button_GoSave"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView_Display" />

    <Button
        android:id="@+id/button_Clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清除已存的資料"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button_GoSave"
        app:layout_constraintTop_toBottomOf="@+id/textView_Display" />

    <Button
        android:id="@+id/button_GoSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="去儲存資料"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline2" />
</androidx.constraintlayout.widget.ConstraintLayout>

 


 

SaveDataActivity.java

截圖 2020-07-11 下午6.03.50

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SaveDataActivity">

    <EditText
        android:id="@+id/editText_Input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="請輸入想儲存的資料"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.6" />

    <Button
        android:id="@+id/button_Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="儲存"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline" />
</androidx.constraintlayout.widget.ConstraintLayout>

 


 

3. 程式內容

在PO全部的程式前,要先來寫幾個主要程式內容

 

我在範例中,已經把功能寫成副程式了

首先是寫:

private boolean write(String s){
    if (s.length() == 0) return false;
    /**創建SharedPreferences,索引為"Data"*/
    SharedPreferences sharedPreferences= getSharedPreferences("Data", Context.MODE_PRIVATE);
    /**取得SharedPreferences.Editor編輯內容*/
    SharedPreferences.Editor editor = sharedPreferences.edit();
    /**放入字串,並定義索引為"Saved"*/
    editor.putString("Saved",s);
    /**提交;提交結果將會回傳一布林值*/
    /**若不需要提交結果,則可使用.apply()*/
    return editor.commit();
}

 

再來是讀:

private String read(){
    /**創建SharedPreferences,索引為"Data"*/
    SharedPreferences sharedPreferences = getSharedPreferences("Data", Context.MODE_PRIVATE);
    /**回傳在"Saved"索引之下的資料;若無儲存則回傳"未存任何資料"*/
    return sharedPreferences.getString("Saved","未存任何資料");
}

 

最後是清除資料:

private void clear(){
    /**創建SharedPreferences*/
    SharedPreferences sharedPreferences = getSharedPreferences("Data",Context.MODE_PRIVATE);
    /**取得SharedPreferences.Editor*/
    SharedPreferences.Editor editor = sharedPreferences.edit();
    /**利用clear清除掉所有資料*/
    editor.clear();
    /**不返回結果的提交*/
    /**若需要提交結果,則可使用.commit()*/
    editor.apply();

}

 

最後,就PO全部的內容吧

 


 

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btGoSave,btDisplay,btClear;
        btGoSave = findViewById(R.id.button_GoSave);
        btDisplay = findViewById(R.id.button_Display);
        btClear = findViewById(R.id.button_Clear);
        TextView tvDisplay = findViewById(R.id.textView_Display);

        btGoSave.setOnClickListener(v->{
            Intent intent = new Intent(this,SaveDataActivity.class);
            startActivity(intent);
        });
        btClear.setOnClickListener(v -> {
            clear();
        });
        btDisplay.setOnClickListener(v -> {
            tvDisplay.setText(read());
        });
    }
    private String read(){
        /**創建SharedPreferences,索引為"Data"*/
        SharedPreferences sharedPreferences = getSharedPreferences("Data", Context.MODE_PRIVATE);
        /**回傳在"Saved"索引之下的資料;若無儲存則回傳"未存任何資料"*/
        return sharedPreferences.getString("Saved","未存任何資料");
    }
    private void clear(){
        /**創建SharedPreferences*/
        SharedPreferences sharedPreferences = getSharedPreferences("Data",Context.MODE_PRIVATE);
        /**取得SharedPreferences.Editor*/
        SharedPreferences.Editor editor = sharedPreferences.edit();
        /**利用clear清除掉所有資料*/
        editor.clear();
        /**不返回結果的提交*/
        /**若需要提交結果,則可使用.commit()*/
        editor.apply();

    }
}

 


 

SavedDataActivity.java

public class SaveDataActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_save_data);
        EditText editText = findViewById(R.id.editText_Input);
        Button btSaved = findViewById(R.id.button_Save);
        btSaved.setOnClickListener(v -> {
            boolean ret = write(editText.getText().toString());
            if (ret) finish();
            else Toast.makeText(this, "未輸入資料..", Toast.LENGTH_SHORT).show();
        });


    }
    private boolean write(String s){
        if (s.length() == 0) return false;
        /**創建SharedPreferences,索引為"Data"*/
        SharedPreferences sharedPreferences= getSharedPreferences("Data", Context.MODE_PRIVATE);
        /**取得SharedPreferences.Editor編輯內容*/
        SharedPreferences.Editor editor = sharedPreferences.edit();
        /**放入字串,並定義索引為"Saved"*/
        editor.putString("Saved",s);
        /**提交;提交結果將會回傳一布林值*/
        /**若不需要提交結果,則可使用.apply()*/
        return editor.commit();
    }
}

 


 

結語

一篇平凡無奇的文章(笑)

連自己打完都不知道自己到底在寫三小東西XD

178276

 

姑且還是有在認真的打文章啦!恩!

當時在寫這個的時候,某些程度來說真的也沒遇到什麼問題

真的要講遇到的問題...就是因為這不是很難的功能導致每次寫過就忘XD

然後下一次遇到的時候就又像個孫子一樣跑回去爬文

 

...所以啊,做筆記很重要滴( ´_ゝ`)

 

好啦,今天的文就當廢文看吧,感謝你的點閱!

images

 

arrow
arrow

    碼農日常 發表在 痞客邦 留言(5) 人氣()