show code block

2017年2月17日 星期五

Android元件:SharedPreferences ─ 儲存資料的好幫手



今日時做影片:





主要程式碼:
SharedPreferences sharedPreferences = getSharedPreferences(String name, int mode);

String name:是你要儲存在手機內的檔案名稱。
Int mode:是你儲存的方式,通常都是使用MODE_PRIVATE(除了你這個app其他app不能使用)

各種MODE
Sr.No
Mode & description
1
MODE_APPEND
This will append the new preferences with the already existing preferences
2
MODE_ENABLE_WRITE_AHEAD_LOGGING
Database open flag. When it is set , it would enable write ahead logging by default
3
MODE_MULTI_PROCESS
This method will check for modification of preferences even if the sharedpreference instance has already been loaded
4
MODE_PRIVATE
By setting this mode, the file can only be accessed using calling application
5
MODE_WORLD_READABLE
This mode allow other application to read the preferences
6
MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences


儲存方式:
SharedPreferences sharedPreferences = getSharedPreferences(data, MODE_PRIVATE);

假設你在EditText內打了一串東西想之後打開app之後還留存。


sharedPreferences.edit()
     .putString(“I_WANT_TO_SAVE_EDIT”, OneEdit.getText().toString())
     .apply();

呼叫sharedPreferences在後面加一個eidt()  (英文大補帖: edit 編輯 )
仔使用putstring 加入你要處存的東西
apply 使它生效(英文大補帖: apply  始生效 )
這就存起來了。
它會存在叫“I_WANT_TO_SAVE_EDIT”的檔案內。

讀取方式:


OneEdit.setText(sharedPreferences.getString(“I_WANT_TO_SAVE_EDIT”, ""));




同場加映

固定Switch開關的問題。

當我讓SWITCH開關成開啟狀態,當下次開啟APP時,要如何保持在開啟狀態呢?


當然是先在xml 內畫一個 switchButton


activity_main.xml
  <Switch
        android:id="@+id/switch_button"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

MainActivity.java

先設定元件
private Switch switch_buton;

指定給xml
switch_buton = (Switch) findViewById(R.id.switch_button);

設定SwitchButton的點擊方式

 switch_buton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_buton.isChecked()) {
                    //如果SwitchButton開啟 do something

                    //儲存
                    sharedPreferences.edit().putBoolean(switchField, true).apply();
                    Log.d(handle, "onClick isChecked switchField= is Open");
                } else {
                    //如果SwitchButton關閉 do something

                    //儲存
                    sharedPreferences.edit().putBoolean(switchField, false).apply();
                    Log.d(handle, "onClick isClosed switchField= is Closed");
                }
            }
        });

然後再OnCreate的地方丟入,這行是指你開啟APP時,讀取你存在sharedPreferences內的SWITCH 狀態。
switch_buton.setChecked(sharedPreferences.getBoolean(switchField, false));

這樣SwitchButton就可以正常開關囉!




完整程式碼:
activity_main.xml
<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.chat.a015865.sharedpreferences.MainActivity">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="1" />

    <EditText
        android:id="@+id/oneField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
      />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="2" />

    <EditText
        android:id="@+id/twoField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
       />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="3" />

    <EditText
        android:id="@+id/threeField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
       />

    <Switch
        android:id="@+id/switch_button"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

    <Button
        android:id="@+id/close_button"
        android:text="關閉app"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>



MainActivity.java
public class MainActivity extends AppCompatActivity {

    private static final String handle = MainActivity.class.getSimpleName();

    private EditText OneEdit, TWO, THREE;
    private Context context;
    private Button close_Button;
    private Activity activity;

    private SharedPreferences sharedPreferences;
    private static final String data = "DATA";
    private static final String helloField = "ONE_STATE";
    private static final String twoField = "TWO_STATE";
    private static final String threeField = "THREE_SATE";
    private static final String switchField = "SWITCH_STATE";

    private Switch switch_buton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        activity = this;
        initView();
        initSet();
        readData();//讀取
    }

    private void initView() {
        close_Button = (Button) findViewById(R.id.close_button);
        sharedPreferences = getSharedPreferences(data, MODE_PRIVATE);
        switch_buton = (Switch) findViewById(R.id.switch_button);
        OneEdit = (EditText) findViewById(R.id.oneField);
        TWO = (EditText) findViewById(R.id.twoField);
        THREE = (EditText) findViewById(R.id.threeField);
    }

    private void initSet() {
        switch_buton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switch_buton.isChecked()) {
                    //如果SwitchButton開啟 do something

                    //儲存
                    sharedPreferences.edit().putBoolean(switchField, true).apply();
                    Log.d(handle, "onClick isChecked switchField= is Open");
                } else {
                    //如果SwitchButton關閉 do something

                    //儲存
                    sharedPreferences.edit().putBoolean(switchField, false).apply();
                    Log.d(handle, "onClick isClosed switchField= is Closed");
                }
            }
        });

        close_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public void readData() {//讀取
        switch_buton.setChecked(sharedPreferences.getBoolean(switchField, false));
        OneEdit.setText(sharedPreferences.getString(helloField, ""));
        TWO.setText(sharedPreferences.getString(twoField, ""));
        THREE.setText(sharedPreferences.getString(threeField, ""));
    }

    public void saveData() {//儲存
        sharedPreferences.edit()
                .putString(helloField, OneEdit.getText().toString())
                .putString(twoField, TWO.getText().toString())
                .putString(threeField, THREE.getText().toString())
                .apply();
    }


    @Override
    protected void onPause() {
        super.onPause();
        Log.d(handle, "onPause()");
        saveData();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(handle, "onStop()");
        saveData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(handle, "onDestroy()");
        saveData();
    }
}





Demo下載:
https://drive.google.com/open?id=0Byk75IYx-dKXMDZZcHFHY3U4SXc
有問題請發問囉!


沒有留言:

張貼留言

協程(coroutine) - 協程為什麼要學它?

 Coroutine 協程 再強調一次 協程就是由kotlin官方所提供的線程api //Thread Thread { }.start() //Executor val execu...