【Android】SharedPreferences的使用

一些簡單的小量數據可以用SharedPreferences存儲,比如說APP的配置文件

一、layout佈局

就放兩個button,一個存,一個取

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="save_SP"/>
    <Button
        android:id="@+id/read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="read_SP"/>

</LinearLayout>

二、Java代碼

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button save, read;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        save = findViewById(R.id.save);
        read = findViewById(R.id.read);
        save.setOnClickListener(this);
        read.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        //存儲文件
            case R.id.save:
                //設置文件名和寫入模式(MODE_PRIVATE是默認的)
                SharedPreferences.Editor editor = getSharedPreferences("test",MODE_PRIVATE).edit();
                //插入數據,第一個是鍵,第二個是值
                editor.putString("name","柳夢璃");//插入String
                editor.putInt("height",163);//插入int,還有editor.putFloat(),editor.putLong()
                editor.putBoolean("marry",false);//插入boolean
                editor.apply();//一定不要忘了提交數據
                break;
         //讀取文件       
            case R.id.read:
                SharedPreferences preferences = getSharedPreferences("test",MODE_PRIVATE);
                //讀取數據,第一個是鍵,第二個是默認值(就是讀取中沒有那個值就使用傳入的默認值)
                String name = preferences.getString("name","不知名");
                int height = preferences.getInt("height",160);
                boolean marry = preferences.getBoolean("marry",false);
                Log.e("2222", "name:"+name+",height:"+height+",marry:"+marry);
                break;
            default:
                break;
        }
    }
}

其他存取文件的方式可以參考

【Android】文本文件的簡單存儲和讀取

【Adnroid】讀取raw的txt等文本文件

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