天天看點

第一行代第六章——詳解持久化技術6.1 持久化技術簡介6.2檔案存儲6.3 SharedPreferences存儲6.4 SQLite資料庫存儲

知識點目錄

  • 6.1 持久化技術簡介
  • 6.2檔案存儲
    • 6.2.1将資料存儲到檔案中
    • 6.2.2 從檔案中讀取資料
  • 6.3 SharedPreferences存儲
    • 6.3.1 将資料存儲到SharedPreferences中
  • 6.4 SQLite資料庫存儲
    • 6.4.1 建立資料庫

6.1 持久化技術簡介

Android主要提供了3種方式用于實作資料持久化功能:

● 檔案存儲

● SharedPreferences存儲

● 資料庫存儲

當然也可以存儲到手機SD卡中,但使用上面的三種來儲存資料會相對簡單一些,也比存儲在SD卡中更加安全。

6.2檔案存儲

檔案存儲是Android中最基本的一種資料存儲方式,有如下特點:

不會對存儲的内容進行任何格式化處理,所有資料都是原封不動地儲存到檔案中

适合存儲一些簡單的文本資料或二進制資料

如果來儲存一些較為複雜的文本資料,就需要定義一套自己的格式規範

6.2.1将資料存儲到檔案中

Context類中提供了一個openFileOutput()方法,可以用于将資料存儲到指定的檔案中。該方法接收兩個參數:

參數一:檔案名。檔案不可包含路徑,因為所有的檔案都是預設存儲到/data/data/包名/files/目錄下。

參數二:檔案的操作模式。有MODE_PRIVATE和MODE_APPEND兩種

MODE_PRIVATE

預設的操作模式,表示當指定同樣檔案名的時候,所寫入的内容将會覆寫原檔案中的内容。

MODE_APPEND

如果檔案已經存在,則直接在檔案中追加内容,不存在就建立新的檔案。

6.2.2 從檔案中讀取資料

Context類中提供了一個openFileInput()方法,用于從檔案中讀取資料。該方法隻接收一個參數,即要讀取的檔案名。

例子:從寫入讀去檔案

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "file";
    private EditText editText;
    private TextView textView;
    private Button write;
    private Button read;
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        write = findViewById(R.id.write);
        read = findViewById(R.id.read);
        write.setOnClickListener(this);
        read.setOnClickListener(this);
    }

    public void onSaveFile() {
        try {
            FileOutputStream fileOutputStream = this.openFileOutput("data.txt",Context.MODE_PRIVATE);
            String string = editText.getText().toString();
            fileOutputStream.write(string.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void onShowFile() {
        try {
            FileInputStream fileInputStream = this.openFileInput("data.txt");
            byte[] bytes =new byte[fileInputStream.available()];
            fileInputStream.read(bytes);
            String string = new String(bytes);
            textView.setText(string);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.read:
                onShowFile();
                break;
            case R.id.write:
                onSaveFile();
                break;
        }
    }

           

xml

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/editText"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:autofillHints="請輸入:">
    </EditText>
    <Button
        android:id="@+id/write"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="write"
        android:textAllCaps="true">
    </Button>
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </TextView>
    <Button
        android:id="@+id/read"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="read"
        android:textAllCaps="true">
    </Button>
</LinearLayout>
           
第一行代第六章——詳解持久化技術6.1 持久化技術簡介6.2檔案存儲6.3 SharedPreferences存儲6.4 SQLite資料庫存儲

6.3 SharedPreferences存儲

SharedPreferences是使用鍵值對的方式來存儲資料的。

6.3.1 将資料存儲到SharedPreferences中

要使用SharedPreferences來存儲資料,首先需要擷取到SharedPreferences對象。Android中主要提供了3種方法用于得到SharedPreferences對象。

1.Context類中的getSharedPreferences()方法

該方法接收兩個參數:

參數一:SharedPreferences檔案名稱,如果檔案名不存在就會建立一個。

SharedPreferences檔案都是存放在/data/data/包名/shared_prefs/目錄下。

參數二:指定操作模式。

目前隻有MODE_PRIVATE這一種模式可選,也是預設的操作模式,和直接傳入0的效果相同。

2. Activity類中的getPreferences()方法

這個方法跟Context類中的getSharedPreferences()方法很相似,但隻接收一個操作模式參數,因為使用這個方法時會自動将目前活動的類名作為SharedPreferences的檔案名

3. PreferenceManager類中的getDefaultSharedPreferences()方法

該方法是一個靜态方法,它接收一個Context參數,并 自動使用目前應用程式的包名作為字首來命名SharedPreferences檔案

例如:

三種方式進行寫入:

//1.context 名字自定
 @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = this.getApplicationContext().getSharedPreferences("data",Context.MODE_PRIVATE).edit();
  editor.putInt("num",123456789);
  editor.apply();

//2 使用Activity 自帶
SharedPreferences.Editor editor1 = this.getPreferences(Context.MODE_PRIVATE).edit();
editor1.putInt("num1",11111);
editor1.apply();

//3. 使用預設的
PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).edit().putInt("com",123).apply();
           

三種方式讀出:

//1.contxt
SharedPreferences sharedPreferences = this.getSharedPreferences("data",Context.MODE_PRIVATE);
int num= sharedPreferences.getInt("num",0);
//2 自帶
SharedPreferences sharedPreferences1 = this.getPreferences(Context.MODE_PRIVATE);
int num1 = sharedPreferences1.getInt("num1",0);
//3 默認
int com = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).getInt("com",0);
           

6.4 SQLite資料庫存儲

Android嵌入了SQLite這一款輕量級的關系型資料庫,它具有如下優點:

● 支援标準的SQL文法

● 遵循資料庫的ACID事務

● 運算速度非常快

● 占用資源很少,通常隻需要幾百KB的記憶體

6.4.1 建立資料庫