android 开发-数据存储之共享参数

android提供5中数据存储方式

  •   数据存储之共享参数     
  •   内部存储
  •   扩展存储
  •   数据库存储
  •   网络存储
 而共享存储提供一种可以让用户存储保存一些持久化键值对在文件中,以供其他应用对这些共享参数进行调用。共享存储的数据类型包括:boolean/float/int/long/String,接下来是我在学习中的示例代码,实例代码中,通过junit进行单元测试,所以需要加入单元测试需要添加的测试包,以及添加单元测试的约束。
  AndroidManifest.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.android_data_storage_share"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="8"
 9         android:targetSdkVersion="18" />
10     <!-- 添加单元测试的约束 -->
11     <instrumentation
12         android:name="android.test.InstrumentationTestRunner"
13         android:targetPackage="com.example.android_data_storage_share" >
14     </instrumentation>
15 
16     <application
17         android:allowBackup="true"
18         android:icon="@drawable/ic_launcher"
19         android:label="@string/app_name"
20         android:theme="@style/AppTheme" >
21 
22         <!-- 单元测试需要添加单元测试包user-library -->
23         <uses-library android:name="android.test.runner" />
24 
25         <activity
26             android:name="com.example.android_data_storage_share.MainActivity"
27             android:label="@string/app_name" >
28             <intent-filter>
29                 <action android:name="android.intent.action.MAIN" />
30 
31                 <category android:name="android.intent.category.LAUNCHER" />
32             </intent-filter>
33         </activity>
34     </application>
35 
36 </manifest>
资源清单文件
  xml:
 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:paddingBottom="@dimen/activity_vertical_margin"
 6     android:paddingLeft="@dimen/activity_horizontal_margin"
 7     android:paddingRight="@dimen/activity_horizontal_margin"
 8     android:paddingTop="@dimen/activity_vertical_margin"
 9     android:background="@drawable/psb"
10     tools:context=".MainActivity" >
11 
12     <TextView
13         android:id="@+id/usView"
14         android:layout_width="wrap_content"
15         android:layout_height="wrap_content"
16         android:layout_alignParentLeft="true"
17         android:layout_alignParentTop="true"
18         android:layout_marginLeft="26dp"
19         android:layout_marginTop="40dp"
20         android:text="用户名:" />
21 
22     <EditText
23         android:id="@+id/usernameText"
24         android:layout_width="wrap_content"
25         android:layout_height="wrap_content"
26         android:layout_alignBaseline="@+id/usView"
27         android:layout_alignBottom="@+id/usView"
28         android:layout_toRightOf="@+id/usView"
29         android:ems="10" >
30 
31         <requestFocus />
32     </EditText>
33 
34     <TextView
35         android:id="@+id/psView"
36         android:layout_width="wrap_content"
37         android:layout_height="wrap_content"
38         android:layout_alignLeft="@+id/usView"
39         android:layout_below="@+id/usernameText"
40         android:layout_marginTop="18dp"
41         android:text="密     码:" />
42 
43     <EditText
44         android:id="@+id/passwordText"
45         android:layout_width="wrap_content"
46         android:layout_height="wrap_content"
47         android:layout_alignLeft="@+id/usernameText"
48         android:layout_below="@+id/usernameText"
49         android:ems="10"
50         android:inputType="textPassword" />
51 
52     <CheckBox
53         android:id="@+id/usCheckBox"
54         android:layout_width="wrap_content"
55         android:layout_height="wrap_content"
56         android:layout_alignLeft="@+id/psView"
57         android:layout_below="@+id/passwordText"
58         android:layout_marginTop="29dp"
59         android:text="记住用户名" />
60 
61     <CheckBox
62         android:id="@+id/radioCheckBox"
63         android:layout_width="wrap_content"
64         android:layout_height="wrap_content"
65         android:layout_alignBaseline="@+id/usCheckBox"
66         android:layout_alignBottom="@+id/usCheckBox"
67         android:layout_marginLeft="18dp"
68         android:layout_toRightOf="@+id/usCheckBox"
69         android:text="静音登录" />
70 
71     <Button
72         android:id="@+id/dlButton"
73         android:layout_width="wrap_content"
74         android:layout_height="wrap_content"
75         android:layout_alignLeft="@+id/usCheckBox"
76         android:layout_centerVertical="true"
77         android:text="登录" />
78 
79     <Button
80         android:id="@+id/cancelButton"
81         android:layout_width="wrap_content"
82         android:layout_height="wrap_content"
83         android:layout_alignBaseline="@+id/dlButton"
84         android:layout_alignBottom="@+id/dlButton"
85         android:layout_marginLeft="32dp"
86         android:layout_toRightOf="@+id/dlButton"
87         android:text="取消" />
88 
89 </RelativeLayout>
xml

  activity:

 1 package com.example.android_data_storage_share;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 import android.app.Activity;
 7 import android.content.Context;
 8 import android.os.Bundle;
 9 import android.view.Menu;
10 import android.view.View;
11 import android.widget.Button;
12 import android.widget.CheckBox;
13 import android.widget.EditText;
14 
15 import com.example.android_data_storage_share.perference.LoginService;
16 
17 /**
18  * @author xiaowu 
19  * @see  文件不要加后缀名,系统自动以.xml的文件保存 第一种方式:getSharedPreferences(name,
20  *         int);共享参数是通过一个标识符来命名,这个文件是多个应用程序访问的,
21  *         第二种方式:getPreferences(int)共享文件只给你当前的activity访问
22  */
23 public class MainActivity extends Activity {
24     private Button dlButton;
25     private Button cancelButton;
26     private EditText usernameText;
27     private EditText passwordText;
28     private CheckBox usCheckBox;
29     private CheckBox radioCheckBox;
30     private LoginService loginService;
31     private Map<String, ?> map = null;
32 
33     @Override
34     protected void onCreate(Bundle savedInstanceState) {
35         super.onCreate(savedInstanceState);
36         setContentView(R.layout.activity_main);
37         loginService = new LoginService(this);
38         dlButton = (Button) findViewById(R.id.dlButton);
39         cancelButton = (Button) findViewById(R.id.cancelButton);
40         usernameText = (EditText) findViewById(R.id.usernameText);
41         passwordText = (EditText) findViewById(R.id.passwordText);
42         usCheckBox = (CheckBox) findViewById(R.id.usCheckBox);
43         radioCheckBox = (CheckBox) findViewById(R.id.radioCheckBox);
44         map = loginService.getSharePreference("login");
45         if (map != null && !map.isEmpty()) {
46             usernameText.setText(map.get("username").toString());
47             passwordText.setText(map.get("password").toString());
48             usCheckBox.setChecked((Boolean) map.get("isName"));
49             radioCheckBox.setChecked((Boolean) map.get("isquiet"));
50         } else {
51             dlButton.setOnClickListener(new View.OnClickListener() {
52                 @Override
53                 public void onClick(View v) {
54                     // TODO Auto-generated method stub
55                     if (usernameText.getText().toString().trim()
56                             .equals("admin")
57                             && passwordText.getText().toString().trim()
58                                     .equals("123456")) {
59                         Map<String, Object> map = new HashMap<String, Object>();
60                         if(usCheckBox.isChecked()){
61                             map.put("username", usernameText.getText().toString()
62                                     .trim());
63                             map.put("password", passwordText.getText().toString()
64                                     .trim());
65                         }else{
66                             map.put("username", "");
67                             map.put("password", "");
68                         }
69                         map.put("isName", usCheckBox.isChecked());
70                         map.put("isquiet", radioCheckBox.isChecked());
71                         loginService.saveSharePreference("login", map);
72                     }
73                 }
74             });
75         }
76 
77     }
78 
79 }

  Service

  

 1 package com.example.android_data_storage_share.perference;
 2 
 3 import java.util.Map;
 4 
 5 import android.content.Context;
 6 import android.content.SharedPreferences;
 7 import android.content.SharedPreferences.Editor;
 8 
 9 public class LoginService {
10 
11     private Context context;
12 
13     public LoginService(Context context) {
14         this.context = context;
15     }
16 
17     public boolean saveLoginMsg(String name, String password) {
18         boolean flag = false;
19         // 文件不要加后缀名,系统自动以.xml的文件保存
20         // 第一种方式:getSharedPreferences(name, int);共享参数是通过一个标识符来命名,这个文件是多个应用程序访问的,
21         // 第二种方式:getPreferences(int)共享文件只给你当前的activity访问
22         // 如果你想要文件既可读又可写,在参数中需要2中权限相加即可context.MODE_WORLD_WRITEABLE+context.MODE_WORLD_READABLE
23         // SharedPreferences sharedPreferences =
24         // context.getSharedPreferences(name,context.MODE_WORLD_WRITEABLE+context.MODE_WORLD_READABLE);
25         SharedPreferences sharedPreferences = context.getSharedPreferences(
26                 name, context.MODE_PRIVATE);
27         Editor editor = sharedPreferences.edit();
28         editor.putString("username", name);
29         editor.putString("password", password);
30         editor.commit();
31         return flag;
32     }
33 
34     /**
35      * (共享储存)存储Map类型的数据
36      * @author xiaowu
37      * @param filename
38      * @param map
39      * @return
40      */
41     public boolean saveSharePreference(String filename, Map<String, Object> map) {
42         SharedPreferences sharedPreferences = context.getSharedPreferences(
43                 filename, Context.MODE_PRIVATE);
44         Editor editor = sharedPreferences.edit();
45         for (Map.Entry<String, Object> entry : map.entrySet()) {
46             String key = entry.getKey();
47             Object object = entry.getValue();
48             if (object instanceof Boolean) {
49                 Boolean new_name = (Boolean) object;
50                 editor.putBoolean(key, new_name);
51             } else if (object instanceof Integer) {
52                 Integer integer = (Integer) object;
53                 editor.putInt(key, integer);
54             } else if (object instanceof Float) {
55                 Float f = (Float) object;
56                 editor.putFloat(key, f);
57             } else if (object instanceof String) {
58                 String s = (String) object;
59                 editor.putString(key, s);
60             } else if (object instanceof Long) {
61                 Long l = (Long) object;
62                 editor.putLong(key, l);
63             }
64         }
65         return editor.commit();
66     }
67 
68     // 读文件权限最低,不需要传递文件操作模式
69     /**
70      * @author xiaowu
71      * @param fileName
72      * @return
73      */
74     public Map<String,?> getSharePreference(String fileName){
75         Map<String,?> map = null;
76         SharedPreferences  sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
77         map = sharedPreferences.getAll();
78         return map;
79     }
80 }

  Test类

  

 1 package com.example;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 import android.test.AndroidTestCase;
 7 import android.util.Log;
 8 
 9 import com.example.android_data_storage_share.perference.LoginService;
10 
11 /**
12  * @author xiaowu Note:必须继承AndroidTestCase这个class
13  */
14 public class MyTest extends AndroidTestCase {
15     private final String TAG = "MyTest";
16     
17     public MyTest() {
18         // TODO Auto-generated constructor stub
19     }
20     //通过方法名右键执行单元测试
21     public void save() {
22         LoginService service = new LoginService(getContext());
23         boolean flag = service.saveLoginMsg("admin", "123");
24         Log.i(TAG, "->>" + flag);
25     }
26     
27     //通过方法名右键执行单元测试
28     public void save2() {
29         LoginService service = new LoginService(getContext());
30         Map<String,Object> map = new HashMap<String, Object>();
31         map.put("name", "hw");
32         map.put("age", 12);
33         map.put("salary", 3000.0f);
34         map.put("id", 430381199007086018l);
35         map.put("isMan", true);
36         boolean flag = service.saveSharePreference("msg", map);
37         Log.i(TAG, "->>" + flag);
38     }
39     //取文件中的值
40     public void read(){
41         LoginService service = new LoginService(getContext());
42         Map<String,?> map = service.getSharePreference("msg");
43         Log.i(TAG, "--->"+map.get("name"));
44         Log.i(TAG, "--->"+map.get("age"));
45         Log.i(TAG, "--->"+map.get("salary"));
46         Log.i(TAG, "--->"+map.get("id"));
47         Log.i(TAG, "--->"+map.get("isMan"));
48     }
49 }

  

posted @ 2015-03-27 09:02  HEWU  阅读(908)  评论(0编辑  收藏  举报