前言
起初再開發APP時發現到,很多Activity都有宣告相同變數,原先都是利用Bundle把值代到下一個Activity,但總覺得這方法有點不好,於是去Google看看有什麼方法可以把變數値存下來,這邊大致總結有5種方法:
- 使用static變數 – 先告一個靜態變數,其他Activity可直接用他 (通常不推薦,除非特殊需求)
- 使用Text檔案 – 產生一個txt把值存在裡面 (通常不推薦,除非特殊需求)
- SharedPreferences – 會產生XML來存取資料以Key-Value方式(本篇介紹)
- Global Variable 使用Application Context来保存全域變數
- SQLite – 本地資料庫,視情況使用
1.Shared Preferences
Shared Preferencesf是一個非常簡單又好用的東西,不僅能當作全域變數來使用,也能當簡易型資料庫來使用,因為他不會因為關閉APP而造成資料流失。
建立
透過getSharedPreferences來建立或取得XML,當執行getSharedPreferences系統就會在/data/[package.name]/shared_prefs/建立一個xml檔案,此方法需要傳入兩個參數getSharedPreferences(String name, int mode)
name為XML檔案名稱
mode可以是以下三參數
- MODE_PRIVATE : 只有此程式可以存取
- MODE_WORLD_READABLE : 其它程式也可以讀取 ( API level 17 中被拋棄了)
- MODE_WORLD_WRITEABLE : 其它程式可以寫入 ( API level 17 中被拋棄了)
1 |
SharedPreferences sharedPreferences = getSharedPreferences("User" , MODE_PRIVATE); |
儲存or修改
接著依照要你要存入的參數型態來使用put,例如putString(key,value)
1 2 |
sharedPreferences.edit().putString("Name", "Devin").apply(); sharedPreferences.edit().putInt("Age", 19).apply(); |
移除
移除對應的KEY資料
1 |
sharedPreferences.editor.remove("Age").commit(); |
MainActivity輸入身高、體重利用Shared Preferences記錄下來
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="test.com.myapplication.CountBMI"> <TextView android:id="@+id/tv3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignRight="@+id/button1" android:layout_below="@+id/button1" android:text="結果:" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/tv4" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignRight="@+id/button1" android:layout_below="@+id/tv3" android:layout_marginTop="10dp" android:text="診斷:" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:text="上一次結果:" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="14dp" android:id="@+id/tv5" android:layout_below="@+id/tv4" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:textSize="18sp" /> </RelativeLayout> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package test.com.myapplication; import android.content.Intent; 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.EditText; import java.text.NumberFormat; public class MainActivity extends AppCompatActivity { EditText h; //宣告全域變數 EditText w; //宣告全域變數 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); h = (EditText)findViewById(R.id.et1); // 取得身高物件 w = (EditText)findViewById(R.id.et2); // 取得體重物件 Button submit = (Button)findViewById(R.id.button1); // 取得按鈕物件 // 按下按鈕 觸發事件 submit.setOnClickListener(new Button.OnClickListener() { public void onClick(View arg0) { //判斷條件 身高 跟 體重 都有輸入值才執行 if ( !("".equals(h.getText().toString()) || "".equals(w.getText().toString())) ) { SharedPreferences sharedPreferences = getSharedPreferences("data" , MODE_PRIVATE); sharedPreferences.edit().putString("height", h.getText().toString()).apply(); sharedPreferences.edit().putString("width" , w.getText().toString()).apply(); Intent intent = new Intent(); intent.setClass(MainActivity.this,CountBMI.class); startActivity(intent); } } }); } } |
CountBMI取出Shared Preferences身高、體重去計算BMI值並記錄下來,當下一次操作時會帶出上一次輸入的BMI值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="test.com.myapplication.CountBMI"> <TextView android:id="@+id/tv3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignRight="@+id/button1" android:layout_below="@+id/button1" android:text="結果:" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/tv4" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignRight="@+id/button1" android:layout_below="@+id/tv3" android:layout_marginTop="10dp" android:text="診斷:" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:text="上一次結果:" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="14dp" android:id="@+id/tv5" android:layout_below="@+id/tv4" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:textSize="18sp" /> </RelativeLayout> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.text.NumberFormat; public class CountBMI extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_count_bmi); //建立SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences("data" , MODE_PRIVATE); //取得身高、體重 String h = sharedPreferences.getString("height" , "0"); String w = sharedPreferences.getString("width" , "0"); float fh = Float.parseFloat(h); // 取得 身高輸入值 float fw = Float.parseFloat(w); // 取得 體重輸入值 float fresult; // BMI值 計算結果 TextView result = (TextView)findViewById(R.id.tv3);// 取得 顯示結果 物件 fh = fh/100; // 計算BMI fh = fh*fh; // 計算BMI NumberFormat nf = NumberFormat.getInstance(); // 數字格式 nf.setMaximumFractionDigits(2); // 限制小數第二位 fresult = fw/fh; // 計算BMI result.setText(nf.format(fw/fh) ); // 顯示BMI計算結果 TextView dia = (TextView)findViewById(R.id.tv4);// 取得 顯示診斷 物件 TextView ldia = (TextView)findViewById(R.id.tv5);// 取得 顯示診斷 物件 ldia.setText( ldia.getText() + sharedPreferences.getString("BMI" , "")); sharedPreferences.edit().putString("BMI" ,nf.format(fw/fh) ).apply(); // 診斷結果 顯示 if (fresult<18.5) dia.setText("體重過輕"); else if (18.5 <= fresult && fresult< 24) dia.setText("正常範圍"); else if (24 <=fresult && fresult < 27) dia.setText("過 重"); else if (27 <=fresult && fresult < 30) dia.setText("輕度肥胖"); else if (30 <= fresult && fresult < 35) dia.setText("中度肥胖"); else if (fresult >= 35) dia.setText("重度肥胖 "); } } |