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

相关文章

C#实现将XML数据自动化地写入Excel文件

《C#实现将XML数据自动化地写入Excel文件》在现代企业级应用中,数据处理与报表生成是核心环节,本文将深入探讨如何利用C#和一款优秀的库,将XML数据自动化地写入Excel文件,有需要的小伙伴可以... 目录理解XML数据结构与Excel的对应关系引入高效工具:使用Spire.XLS for .NETC

MySQL数据目录迁移的完整过程

《MySQL数据目录迁移的完整过程》文章详细介绍了将MySQL数据目录迁移到新硬盘的整个过程,包括新硬盘挂载、创建新的数据目录、迁移数据(推荐使用两遍rsync方案)、修改MySQL配置文件和重启验证... 目录1,新硬盘挂载(如果有的话)2,创建新的 mysql 数据目录3,迁移 MySQL 数据(推荐两

Python数据验证神器Pydantic库的使用和实践中的避坑指南

《Python数据验证神器Pydantic库的使用和实践中的避坑指南》Pydantic是一个用于数据验证和设置的库,可以显著简化API接口开发,文章通过一个实际案例,展示了Pydantic如何在生产环... 目录1️⃣ 崩溃时刻:当你的API接口又双叒崩了!2️⃣ 神兵天降:3行代码解决验证难题3️⃣ 深度

MySQL快速复制一张表的四种核心方法(包括表结构和数据)

《MySQL快速复制一张表的四种核心方法(包括表结构和数据)》本文详细介绍了四种复制MySQL表(结构+数据)的方法,并对每种方法进行了对比分析,适用于不同场景和数据量的复制需求,特别是针对超大表(1... 目录一、mysql 复制表(结构+数据)的 4 种核心方法(面试结构化回答)方法 1:CREATE

详解C++ 存储二进制数据容器的几种方法

《详解C++存储二进制数据容器的几种方法》本文主要介绍了详解C++存储二进制数据容器,包括std::vector、std::array、std::string、std::bitset和std::ve... 目录1.std::vector<uint8_t>(最常用)特点:适用场景:示例:2.std::arra

Android使用java实现网络连通性检查详解

《Android使用java实现网络连通性检查详解》这篇文章主要为大家详细介绍了Android使用java实现网络连通性检查的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录NetCheck.Java(可直接拷贝)使用示例(Activity/Fragment 内)权限要求

MySQL中的DELETE删除数据及注意事项

《MySQL中的DELETE删除数据及注意事项》MySQL的DELETE语句是数据库操作中不可或缺的一部分,通过合理使用索引、批量删除、避免全表删除、使用TRUNCATE、使用ORDERBY和LIMI... 目录1. 基本语法单表删除2. 高级用法使用子查询删除删除多表3. 性能优化策略使用索引批量删除避免

2025最新版Android Studio安装及组件配置教程(SDK、JDK、Gradle)

《2025最新版AndroidStudio安装及组件配置教程(SDK、JDK、Gradle)》:本文主要介绍2025最新版AndroidStudio安装及组件配置(SDK、JDK、Gradle... 目录原生 android 简介Android Studio必备组件一、Android Studio安装二、A

MySQL 数据库进阶之SQL 数据操作与子查询操作大全

《MySQL数据库进阶之SQL数据操作与子查询操作大全》本文详细介绍了SQL中的子查询、数据添加(INSERT)、数据修改(UPDATE)和数据删除(DELETE、TRUNCATE、DROP)操作... 目录一、子查询:嵌套在查询中的查询1.1 子查询的基本语法1.2 子查询的实战示例二、数据添加:INSE

Linux服务器数据盘移除并重新挂载的全过程

《Linux服务器数据盘移除并重新挂载的全过程》:本文主要介绍在Linux服务器上移除并重新挂载数据盘的整个过程,分为三大步:卸载文件系统、分离磁盘和重新挂载,每一步都有详细的步骤和注意事项,确保... 目录引言第一步:卸载文件系统第二步:分离磁盘第三步:重新挂载引言在 linux 服务器上移除并重新挂p