Android數據存儲之SharedPreferencesSave存儲(保存數據,讀取數據的操作)

GitHub項目地址:

https://github.com/Skymqq/SharedPreferencesSave.git

不同於文件的存儲方式,SharedPreferences是使用鍵值對的方式來存儲數據的。也就是說,當保存一條數據的時候,需要給這條數據提供一個對應的鍵,這樣在讀取數據的時候就可以通過這個鍵把相應的值取出來。而且SharePreferences還支持多種不同的數據類型存儲,如果存儲的數據類型是整型,那麼讀取出來的數據也是整型的;如果存儲的數據是一個字符串,那麼讀取出來的數據仍然是字符串。

這樣你應該就能很明顯地感覺到,使用SharedPreferences來進行數據持久化要比使用文件更方便很多,下面我們就來看一下它的具體用法。

要想使用SharedPreferences來存儲數據,首先需要獲取到SharedPreferences對象。Android中主要提供了3中方法用於得到SharedPreferences對象。

1.Context類中的getSharedPreferences()方法

此方法接收兩個參數,第一個參數用於指定SharedPreferences文件的名稱,如果指定的文件不存在則會自動創建一個,SharedPreferences文件都是存放在data/data/<package name>/shared_prefs/目錄下的。第二個參數用於指定操作模式,目前只有MODE_PRIVATE這一種模式可以選擇,它是默認的操作模式,和直接傳入0的效果是相同的,表示只有當前的應用程序纔可以對這個SharedPreferences文件進行讀寫。其他幾種操作模式均已被廢棄,MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE這兩種模式是在Android4.2版本中被廢棄的,MODE_MULTI_PROCESS模式是在Android6.0版本中被廢棄的。

2.Activity類中的getPreferences()方法

這個方法和Context中的getSharedPreferences()方法很相似,不過它只接收一個操作模式參數,因爲使用這個方法時會自動將當前活動的類名作爲SharedPreferences的文件名。

3.PreferenceManager類中的getDefaultSharedPreferences()方法

這是一個靜態方法,它接收一個Context參數,並自動使用當前應用程序的包名作爲前綴來命名SharedPreferences文件。得到了SharedPreferences對象之後,就可以開始向SharedPreferences文件中存儲數據了,主要可以分未步來實現。

(1)調用SharedPreferences對象的edit()方法來獲取一個SharedPreferences.Editor對象。

(2)向SharedPreferences.Editor對象中添加數據,比如添加一個布爾型數據就使用putBoolean()方法,添加一個字符串則使用putString()方法,以此類推。

下面我們新建一個SharedPreferencesSave項目,然後在activity_main.xml中添加一個Button控件。

activity_main.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:orientation="vertical">

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SPSave"
        android:textAllCaps="false"
        android:textSize="20sp"
        android:textStyle="bold" />
</LinearLayout>

 MainActivity.java代碼:

package com.example.administrator.sharedpreferencessave;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn = (Button) findViewById(R.id.btn);
    }

    @Override
    protected void onResume() {
        super.onResume();
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
                Toast.makeText(MainActivity.this, "data already saved in sp", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void save() {
        SharedPreferences.Editor editor = this.getSharedPreferences("data", MODE_PRIVATE).edit();
        editor.putString("name", "Tom");
        editor.putInt("age", 28);
        editor.putBoolean("married", false);
        editor.apply();
    }
}

可以看到,這裏首先給按鈕註冊了一個點擊事件,然後在點擊事件中通過getSharedPreferences()方法指定SharedPreferences文件名爲data,並得到了SharedPreferences.Editor對象。接着向這個對象中添加了3條不同類型的數據,最後調用apply()方法進行提交,從而完成了數據存儲的操作。

運行程序,點擊Button按鈕,效果圖如下所示:

 

在Device File Explorer中找到data.xml文件,打開如下所示:

從SharedPreferences中讀取數據

修改activity_main.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:orientation="vertical">

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SPSave"
        android:textAllCaps="false"
        android:textSize="20sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SPRead"
        android:textAllCaps="false"
        android:textSize="20sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="name: "
            android:textAllCaps="false"
            android:textSize="15sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="name"
            android:textAllCaps="false"
            android:textSize="25sp"
            android:textStyle="bold" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="age: "
            android:textAllCaps="false"
            android:textSize="15sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="age"
            android:textAllCaps="false"
            android:textSize="25sp"
            android:textStyle="bold" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="married: "
            android:textAllCaps="false"
            android:textSize="15sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_married"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="married"
            android:textAllCaps="false"
            android:textSize="25sp"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>

MainActivity.java代碼:

package com.example.administrator.sharedpreferencessave;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button btn, btn_read;
    private TextView tv_name, tv_age, tv_married;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn = (Button) findViewById(R.id.btn);
        btn_read = (Button) findViewById(R.id.btn_read);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_age = (TextView) findViewById(R.id.tv_age);
        tv_married = (TextView) findViewById(R.id.tv_married);
    }

    @Override
    protected void onResume() {
        super.onResume();
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();//將數據保存入本地sp
                Toast.makeText(MainActivity.this, "data already saved in sp", Toast.LENGTH_SHORT).show();
            }
        });

        btn_read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                read();//將數據從本地sp中讀取出來並顯示
            }
        });
    }

    private void save() {
        SharedPreferences.Editor editor = this.getSharedPreferences("data", MODE_PRIVATE).edit();
        editor.putString("name", "Tom");
        editor.putInt("age", 28);
        editor.putBoolean("married", false);
        editor.apply();
    }

    private void read() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
                String name = sp.getString("name", "");
                int age = sp.getInt("age", 0);
                boolean married = sp.getBoolean("married", false);
                tv_name.setText("" + name);
                tv_age.setText("" + age);
                tv_married.setText("" + married);
                Toast.makeText(MainActivity.this, "data already read in sp", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

效果圖:

點擊SPRead按鈕,讀取本地SP中的數據,並更新UI顯示:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章