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

相关文章

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

MyBatisPlus如何优化千万级数据的CRUD

《MyBatisPlus如何优化千万级数据的CRUD》最近负责的一个项目,数据库表量级破千万,每次执行CRUD都像走钢丝,稍有不慎就引起数据库报警,本文就结合这个项目的实战经验,聊聊MyBatisPl... 目录背景一、MyBATis Plus 简介二、千万级数据的挑战三、优化 CRUD 的关键策略1. 查

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

MySQL之InnoDB存储引擎中的索引用法及说明

《MySQL之InnoDB存储引擎中的索引用法及说明》:本文主要介绍MySQL之InnoDB存储引擎中的索引用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录1、背景2、准备3、正篇【1】存储用户记录的数据页【2】存储目录项记录的数据页【3】聚簇索引【4】二

mysql中的数据目录用法及说明

《mysql中的数据目录用法及说明》:本文主要介绍mysql中的数据目录用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、版本3、数据目录4、总结1、背景安装mysql之后,在安装目录下会有一个data目录,我们创建的数据库、创建的表、插入的

MySQL之InnoDB存储页的独立表空间解读

《MySQL之InnoDB存储页的独立表空间解读》:本文主要介绍MySQL之InnoDB存储页的独立表空间,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、独立表空间【1】表空间大小【2】区【3】组【4】段【5】区的类型【6】XDES Entry区结构【

SQLite3 在嵌入式C环境中存储音频/视频文件的最优方案

《SQLite3在嵌入式C环境中存储音频/视频文件的最优方案》本文探讨了SQLite3在嵌入式C环境中存储音视频文件的优化方案,推荐采用文件路径存储结合元数据管理,兼顾效率与资源限制,小文件可使用B... 目录SQLite3 在嵌入式C环境中存储音频/视频文件的专业方案一、存储策略选择1. 直接存储 vs

Navicat数据表的数据添加,删除及使用sql完成数据的添加过程

《Navicat数据表的数据添加,删除及使用sql完成数据的添加过程》:本文主要介绍Navicat数据表的数据添加,删除及使用sql完成数据的添加过程,具有很好的参考价值,希望对大家有所帮助,如有... 目录Navicat数据表数据添加,删除及使用sql完成数据添加选中操作的表则出现如下界面,查看左下角从左

SpringBoot中4种数据水平分片策略

《SpringBoot中4种数据水平分片策略》数据水平分片作为一种水平扩展策略,通过将数据分散到多个物理节点上,有效解决了存储容量和性能瓶颈问题,下面小编就来和大家分享4种数据分片策略吧... 目录一、前言二、哈希分片2.1 原理2.2 SpringBoot实现2.3 优缺点分析2.4 适用场景三、范围分片

Redis分片集群、数据读写规则问题小结

《Redis分片集群、数据读写规则问题小结》本文介绍了Redis分片集群的原理,通过数据分片和哈希槽机制解决单机内存限制与写瓶颈问题,实现分布式存储和高并发处理,但存在通信开销大、维护复杂及对事务支持... 目录一、分片集群解android决的问题二、分片集群图解 分片集群特征如何解决的上述问题?(与哨兵模