標籤:android學習筆記之資料的共用儲存s 資料的共用儲存sharedprefere sharedpreferences
(1)布局檔案,一個簡單的登入檔案;
<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=".MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="22dp" android:layout_marginTop="22dp" android:text="使用者名稱:" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView1" android:layout_alignBottom="@+id/textView1" android:layout_toRightOf="@+id/textView1" android:ems="10" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textView1" android:layout_below="@+id/editText1" android:layout_marginTop="17dp" android:text="密碼:" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_below="@+id/editText1" android:ems="10" android:inputType="textPassword" > <requestFocus /> </EditText> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/checkBox1" android:layout_marginLeft="34dp" android:layout_marginTop="32dp" android:layout_toRightOf="@+id/button1" android:text="取消" /> <CheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/editText2" android:layout_marginTop="22dp" android:text="記住使用者名稱" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button2" android:layout_alignBottom="@+id/button2" android:layout_alignLeft="@+id/editText2" android:text="登入" /> <CheckBox android:id="@+id/checkBox2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/checkBox1" android:layout_alignBottom="@+id/checkBox1" android:layout_marginLeft="14dp" android:layout_toRightOf="@+id/button1" android:text="靜音登入" /></RelativeLayout>
(2)目錄結構:
(3)SharedPreferences的工具類LoginService.java
package com.lc.data_storage_share.sharepreference;import java.util.Map;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;public class LoginService {private Context context; // 上下文public LoginService(Context context) {this.context = context;}/* * 儲存登入資訊 */public boolean saveLoginMsg(String name, String password) {boolean flag = false;// 不要加尾碼名,系統自動以.xml的格式儲存// 這裡的login是要存放的檔案名稱SharedPreferences preferences = context.getSharedPreferences("login",context.MODE_PRIVATE + context.MODE_APPEND);Editor editor = preferences.edit();editor.putString("name", name);editor.putString("password", password);flag = editor.commit();return flag;}/* * 儲存檔案 */public boolean saveSharePreference(String filename, Map<String, Object> map) {boolean flag = false;SharedPreferences preferences = context.getSharedPreferences(filename,Context.MODE_PRIVATE);/* * 存資料的時候要用到Editor */Editor editor = preferences.edit();for (Map.Entry<String, Object> entry : map.entrySet()) {String key = entry.getKey();Object object = entry.getValue();if (object instanceof Boolean) {Boolean new_name = (Boolean) object;editor.putBoolean(key, new_name);} else if (object instanceof Integer) {Integer integer = (Integer) object;editor.putInt(key, integer);} else if (object instanceof Float) {Float f = (Float) object;editor.putFloat(key, f);} else if (object instanceof Long) {Long l = (Long) object;editor.putLong(key, l);} else if (object instanceof String) {String s = (String) object;editor.putString(key, s);}}flag = editor.commit();return flag;}/* * 讀取檔案 */public Map<String, ?> getSharePreference(String filename) {Map<String, ?> map = null;SharedPreferences preferences = context.getSharedPreferences(filename,Context.MODE_PRIVATE);/* * 讀資料的餓時候只需要訪問即可 */map = preferences.getAll();return map;}}
(3)MainActivity.java
package com.lc.data_storage_share;import java.util.HashMap;import java.util.Map;import com.example.data_storage_share.R;import com.lc.data_storage_share.sharepreference.LoginService;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;/* * 單元測試的時候需要在資訊清單檔中 */public class MainActivity extends Activity {private Button button1;// 登入private Button button2;// 取消private EditText editText1, editText2;private CheckBox checkBox1;// 記住密碼private CheckBox checkBox2; // 靜音登入private LoginService service;Map<String, ?> map = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button1 = (Button) this.findViewById(R.id.button1);button2 = (Button) this.findViewById(R.id.button2);editText1 = (EditText) this.findViewById(R.id.editText1);editText2 = (EditText) this.findViewById(R.id.editText2);checkBox1 = (CheckBox) this.findViewById(R.id.checkBox1);checkBox2 = (CheckBox) this.findViewById(R.id.checkBox2);service = new LoginService(this);map = service.getSharePreference("login");if (map != null && !map.isEmpty()) {editText1.setText(map.get("username").toString());checkBox1.setChecked((Boolean) map.get("isName"));checkBox2.setChecked((Boolean) map.get("isquiet"));} button1.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif (editText1.getText().toString().trim().equals("admin")) {Map<String, Object> map1 = new HashMap<String, Object>();if (checkBox1.isChecked()) {map1.put("username", editText1.getText().toString().trim());}else {map1.put("username", "");}map1.put("isName", checkBox1.isChecked());map1.put("isquiet", checkBox2.isChecked());service.saveSharePreference("login", map1);}}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
(4)測試類別:
package com.lc.data_storage_share;import java.util.HashMap;import java.util.Map;import android.test.AndroidTestCase;import android.util.Log;import com.lc.data_storage_share.sharepreference.LoginService;public class MyTest extends AndroidTestCase {private final String TAG = "MyTest";public MyTest() {// TODO Auto-generated constructor stub}/* * 登入 */public void save() {LoginService service = new LoginService(getContext());boolean flag = service.saveLoginMsg("admin", "123");Log.i(TAG, "-->>" + flag);}/* * 儲存檔案 */public void saveFile() {LoginService service = new LoginService(getContext());Map<String, Object> map = new HashMap<String, Object>();map.put("name", "jack");map.put("age", 23);map.put("salary", 23000.0f);map.put("id", 1256423132l);map.put("isManager", true);boolean flag = service.saveSharePreference("msg", map);Log.i(TAG, "-->>" + flag);}/* * 讀取檔案 */public void readFile() {LoginService service = new LoginService(getContext());Map<String, ?> map = service.getSharePreference("msg");Log.i(TAG, "-->>" + map.get("name"));Log.i(TAG, "-->>" + map.get("age"));Log.i(TAG, "-->>" + map.get("salary"));Log.i(TAG, "-->>" + map.get("isManager"));Log.i(TAG, "-->>" + map.get("id"));}}
如何添加Junit測試單元:
1.在資訊清單檔中添加:
2.在application中添加:
3.測試類別MyTest要繼承AndroidTestCase
(5)結果,下次登入的時候會記著使用者名稱
Android學習筆記之資料的共用儲存SharedPreferences