当前位置: 首页 > news >正文

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







相关文章:

  • CMD命令下访问Oracle数据库
  • Android学习笔记之数据的内部存储方式实习数据的读写、存储到Cache实现读写
  • JSP详细解析
  • Android学习笔记之数据的Sdcard存储方法及操作sdcard的工具类
  • Construct Binary Tree from Inorder and Postorder Traversal
  • Android学习笔记之Fragment的两种使用方法
  • Android学习笔记之SQLite数据库的使用及常用的增删改查方法、无sql语句的DRUD方法汇总
  • codeforces 455C 并查集
  • Android学习笔记之使用意图打开内置应用程序组件
  • java web sql注入测试(3)---现象分析
  • Android学习笔记之广播意图及广播接收者MyBroadcastReceiver、Broadcast
  • 一些简单的shell脚本实例 转
  • xUtils简介及其使用方法
  • OC基础(20)
  • Android框架Picasso介绍
  • 《Javascript高级程序设计 (第三版)》第五章 引用类型
  • 【108天】Java——《Head First Java》笔记(第1-4章)
  • 【个人向】《HTTP图解》阅后小结
  • CSS 专业技巧
  • Invalidate和postInvalidate的区别
  • javascript面向对象之创建对象
  • JSONP原理
  • miniui datagrid 的客户端分页解决方案 - CS结合
  • ng6--错误信息小结(持续更新)
  • UEditor初始化失败(实例已存在,但视图未渲染出来,单页化)
  • 聚簇索引和非聚簇索引
  • 猫头鹰的深夜翻译:JDK9 NotNullOrElse方法
  • Spring第一个helloWorld
  • 如何在招聘中考核.NET架构师
  • 昨天1024程序员节,我故意写了个死循环~
  • ​一、什么是射频识别?二、射频识别系统组成及工作原理三、射频识别系统分类四、RFID与物联网​
  • $.extend({},旧的,新的);合并对象,后面的覆盖前面的
  • (附源码)计算机毕业设计ssm电影分享网站
  • (论文阅读23/100)Hierarchical Convolutional Features for Visual Tracking
  • (每日持续更新)jdk api之FileReader基础、应用、实战
  • (四)Android布局类型(线性布局LinearLayout)
  • (译)计算距离、方位和更多经纬度之间的点
  • (转)大型网站的系统架构
  • (转载)在C#用WM_COPYDATA消息来实现两个进程之间传递数据
  • (状压dp)uva 10817 Headmaster's Headache
  • .htaccess配置常用技巧
  • .net core 6 集成 elasticsearch 并 使用分词器
  • .Net各种迷惑命名解释
  • .net中的Queue和Stack
  • .Net中的集合
  • @angular/cli项目构建--http(2)
  • @hook扩展分析
  • @JSONField或@JsonProperty注解使用
  • @TableId注解详细介绍 mybaits 实体类主键注解
  • [ MSF使用实例 ] 利用永恒之蓝(MS17-010)漏洞导致windows靶机蓝屏并获取靶机权限
  • [ vulhub漏洞复现篇 ] JBOSS AS 4.x以下反序列化远程代码执行漏洞CVE-2017-7504
  • [Android View] 可绘制形状 (Shape Xml)
  • [Android] Amazon 的 android 音视频开发文档
  • [c]扫雷
  • [CF]Codeforces Round #551 (Div. 2)