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

相关文章

Android Mainline基础简介

《AndroidMainline基础简介》AndroidMainline是通过模块化更新Android核心组件的框架,可能提高安全性,本文给大家介绍AndroidMainline基础简介,感兴趣的朋... 目录关键要点什么是 android Mainline?Android Mainline 的工作原理关键

如何解决idea的Module:‘:app‘platform‘android-32‘not found.问题

《如何解决idea的Module:‘:app‘platform‘android-32‘notfound.问题》:本文主要介绍如何解决idea的Module:‘:app‘platform‘andr... 目录idea的Module:‘:app‘pwww.chinasem.cnlatform‘android-32

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

SpringValidation数据校验之约束注解与分组校验方式

《SpringValidation数据校验之约束注解与分组校验方式》本文将深入探讨SpringValidation的核心功能,帮助开发者掌握约束注解的使用技巧和分组校验的高级应用,从而构建更加健壮和可... 目录引言一、Spring Validation基础架构1.1 jsR-380标准与Spring整合1

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

MySQL 中查询 VARCHAR 类型 JSON 数据的问题记录

《MySQL中查询VARCHAR类型JSON数据的问题记录》在数据库设计中,有时我们会将JSON数据存储在VARCHAR或TEXT类型字段中,本文将详细介绍如何在MySQL中有效查询存储为V... 目录一、问题背景二、mysql jsON 函数2.1 常用 JSON 函数三、查询示例3.1 基本查询3.2

SpringBatch数据写入实现

《SpringBatch数据写入实现》SpringBatch通过ItemWriter接口及其丰富的实现,提供了强大的数据写入能力,本文主要介绍了SpringBatch数据写入实现,具有一定的参考价值,... 目录python引言一、ItemWriter核心概念二、数据库写入实现三、文件写入实现四、多目标写入

Android Studio 配置国内镜像源的实现步骤

《AndroidStudio配置国内镜像源的实现步骤》本文主要介绍了AndroidStudio配置国内镜像源的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、修改 hosts,解决 SDK 下载失败的问题二、修改 gradle 地址,解决 gradle

使用Python将JSON,XML和YAML数据写入Excel文件

《使用Python将JSON,XML和YAML数据写入Excel文件》JSON、XML和YAML作为主流结构化数据格式,因其层次化表达能力和跨平台兼容性,已成为系统间数据交换的通用载体,本文将介绍如何... 目录如何使用python写入数据到Excel工作表用Python导入jsON数据到Excel工作表用

Mysql如何将数据按照年月分组的统计

《Mysql如何将数据按照年月分组的统计》:本文主要介绍Mysql如何将数据按照年月分组的统计方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录mysql将数据按照年月分组的统计要的效果方案总结Mysql将数据按照年月分组的统计要的效果方案① 使用 DA