Android学习笔记之数据的共享存储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;

	@Override
	protected 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() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (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);
				}
			}
		});
	}

	@Override
	public 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)结果,下次登录的时候会记着用户名

技术分享技术分享






郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。