Android学习笔记之数据的共享存储SharedPreferences

2024-05-24 03:18

本文主要是介绍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" ><TextViewandroid: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="用户名:" /><EditTextandroid: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" /><TextViewandroid: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="密码:" /><EditTextandroid: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><Buttonandroid: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="取消" /><CheckBoxandroid: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="记住用户名" /><Buttonandroid: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="登录" /><CheckBoxandroid: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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/997215

相关文章

Mysql数据库中数据的操作CRUD详解

《Mysql数据库中数据的操作CRUD详解》:本文主要介绍Mysql数据库中数据的操作(CRUD),详细描述对Mysql数据库中数据的操作(CRUD),包括插入、修改、删除数据,还有查询数据,包括... 目录一、插入数据(insert)1.插入数据的语法2.注意事项二、修改数据(update)1.语法2.有

SpringBoot实现接口数据加解密的三种实战方案

《SpringBoot实现接口数据加解密的三种实战方案》在金融支付、用户隐私信息传输等场景中,接口数据若以明文传输,极易被中间人攻击窃取,SpringBoot提供了多种优雅的加解密实现方案,本文将从原... 目录一、为什么需要接口数据加解密?二、核心加解密算法选择1. 对称加密(AES)2. 非对称加密(R

详解如何在SpringBoot控制器中处理用户数据

《详解如何在SpringBoot控制器中处理用户数据》在SpringBoot应用开发中,控制器(Controller)扮演着至关重要的角色,它负责接收用户请求、处理数据并返回响应,本文将深入浅出地讲解... 目录一、获取请求参数1.1 获取查询参数1.2 获取路径参数二、处理表单提交2.1 处理表单数据三、

java变量内存中存储的使用方式

《java变量内存中存储的使用方式》:本文主要介绍java变量内存中存储的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍2、变量的定义3、 变量的类型4、 变量的作用域5、 内存中的存储方式总结1、介绍在 Java 中,变量是用于存储程序中数据

重新对Java的类加载器的学习方式

《重新对Java的类加载器的学习方式》:本文主要介绍重新对Java的类加载器的学习方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍1.1、简介1.2、符号引用和直接引用1、符号引用2、直接引用3、符号转直接的过程2、加载流程3、类加载的分类3.1、显示

Spring Validation中9个数据校验工具使用指南

《SpringValidation中9个数据校验工具使用指南》SpringValidation作为Spring生态系统的重要组成部分,提供了一套强大而灵活的数据校验机制,本文给大家介绍了Spring... 目录1. Bean Validation基础注解常用注解示例在控制器中应用2. 自定义约束验证器定义自

Android NDK版本迭代与FFmpeg交叉编译完全指南

《AndroidNDK版本迭代与FFmpeg交叉编译完全指南》在Android开发中,使用NDK进行原生代码开发是一项常见需求,特别是当我们需要集成FFmpeg这样的多媒体处理库时,本文将深入分析A... 目录一、android NDK版本迭代分界线二、FFmpeg交叉编译关键注意事项三、完整编译脚本示例四

C#实现高性能Excel百万数据导出优化实战指南

《C#实现高性能Excel百万数据导出优化实战指南》在日常工作中,Excel数据导出是一个常见的需求,然而,当数据量较大时,性能和内存问题往往会成为限制导出效率的瓶颈,下面我们看看C#如何结合EPPl... 目录一、技术方案核心对比二、各方案选型建议三、性能对比数据四、核心代码实现1. MiniExcel

Android与iOS设备MAC地址生成原理及Java实现详解

《Android与iOS设备MAC地址生成原理及Java实现详解》在无线网络通信中,MAC(MediaAccessControl)地址是设备的唯一网络标识符,本文主要介绍了Android与iOS设备M... 目录引言1. MAC地址基础1.1 MAC地址的组成1.2 MAC地址的分类2. android与I

SQL常用操作精华之复制表、跨库查询、删除重复数据

《SQL常用操作精华之复制表、跨库查询、删除重复数据》:本文主要介绍SQL常用操作精华之复制表、跨库查询、删除重复数据,这些SQL操作涵盖了数据库开发中最常用的技术点,包括表操作、数据查询、数据管... 目录SQL常用操作精华总结表结构与数据操作高级查询技巧SQL常用操作精华总结表结构与数据操作复制表结