android提供5中数据存储方式

  • 数据存储之共享参数
  • 内部存储
  • 扩展存储
  • 数据库存储
  • 网络存储
 而共享存储提供一种可以让用户存储保存一些持久化键值对在文件中,以供其他应用对这些共享参数进行调用。共享存储的数据类型包括:boolean/float/int/long/String,接下来是我在学习中的示例代码,实例代码中,通过junit进行单元测试,所以需要加入单元测试需要添加的测试包,以及添加单元测试的约束。
  AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_data_storage_share"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<!-- 添加单元测试的约束 -->
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.android_data_storage_share" >
</instrumentation> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" > <!-- 单元测试需要添加单元测试包user-library -->
<uses-library android:name="android.test.runner" /> <activity
android:name="com.example.android_data_storage_share.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> </manifest>

资源清单文件

  xml:

 <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"
android:background="@drawable/psb"
tools:context=".MainActivity" > <TextView
android:id="@+id/usView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="26dp"
android:layout_marginTop="40dp"
android:text="用户名:" /> <EditText
android:id="@+id/usernameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/usView"
android:layout_alignBottom="@+id/usView"
android:layout_toRightOf="@+id/usView"
android:ems="10" > <requestFocus />
</EditText> <TextView
android:id="@+id/psView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/usView"
android:layout_below="@+id/usernameText"
android:layout_marginTop="18dp"
android:text="密 码:" /> <EditText
android:id="@+id/passwordText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/usernameText"
android:layout_below="@+id/usernameText"
android:ems="10"
android:inputType="textPassword" /> <CheckBox
android:id="@+id/usCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/psView"
android:layout_below="@+id/passwordText"
android:layout_marginTop="29dp"
android:text="记住用户名" /> <CheckBox
android:id="@+id/radioCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/usCheckBox"
android:layout_alignBottom="@+id/usCheckBox"
android:layout_marginLeft="18dp"
android:layout_toRightOf="@+id/usCheckBox"
android:text="静音登录" /> <Button
android:id="@+id/dlButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/usCheckBox"
android:layout_centerVertical="true"
android:text="登录" /> <Button
android:id="@+id/cancelButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/dlButton"
android:layout_alignBottom="@+id/dlButton"
android:layout_marginLeft="32dp"
android:layout_toRightOf="@+id/dlButton"
android:text="取消" /> </RelativeLayout>

xml

  activity:

 package com.example.android_data_storage_share;

 import java.util.HashMap;
import java.util.Map; import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText; import com.example.android_data_storage_share.perference.LoginService; /**
* @author xiaowu
* @see 文件不要加后缀名,系统自动以.xml的文件保存 第一种方式:getSharedPreferences(name,
* int);共享参数是通过一个标识符来命名,这个文件是多个应用程序访问的,
* 第二种方式:getPreferences(int)共享文件只给你当前的activity访问
*/
public class MainActivity extends Activity {
private Button dlButton;
private Button cancelButton;
private EditText usernameText;
private EditText passwordText;
private CheckBox usCheckBox;
private CheckBox radioCheckBox;
private LoginService loginService;
private Map<String, ?> map = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginService = new LoginService(this);
dlButton = (Button) findViewById(R.id.dlButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
usernameText = (EditText) findViewById(R.id.usernameText);
passwordText = (EditText) findViewById(R.id.passwordText);
usCheckBox = (CheckBox) findViewById(R.id.usCheckBox);
radioCheckBox = (CheckBox) findViewById(R.id.radioCheckBox);
map = loginService.getSharePreference("login");
if (map != null && !map.isEmpty()) {
usernameText.setText(map.get("username").toString());
passwordText.setText(map.get("password").toString());
usCheckBox.setChecked((Boolean) map.get("isName"));
radioCheckBox.setChecked((Boolean) map.get("isquiet"));
} else {
dlButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (usernameText.getText().toString().trim()
.equals("admin")
&& passwordText.getText().toString().trim()
.equals("123456")) {
Map<String, Object> map = new HashMap<String, Object>();
if(usCheckBox.isChecked()){
map.put("username", usernameText.getText().toString()
.trim());
map.put("password", passwordText.getText().toString()
.trim());
}else{
map.put("username", "");
map.put("password", "");
}
map.put("isName", usCheckBox.isChecked());
map.put("isquiet", radioCheckBox.isChecked());
loginService.saveSharePreference("login", map);
}
}
});
} } }

  Service

  

 package com.example.android_data_storage_share.perference;

 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的文件保存
// 第一种方式:getSharedPreferences(name, int);共享参数是通过一个标识符来命名,这个文件是多个应用程序访问的,
// 第二种方式:getPreferences(int)共享文件只给你当前的activity访问
// 如果你想要文件既可读又可写,在参数中需要2中权限相加即可context.MODE_WORLD_WRITEABLE+context.MODE_WORLD_READABLE
// SharedPreferences sharedPreferences =
// context.getSharedPreferences(name,context.MODE_WORLD_WRITEABLE+context.MODE_WORLD_READABLE);
SharedPreferences sharedPreferences = context.getSharedPreferences(
name, context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putString("username", name);
editor.putString("password", password);
editor.commit();
return flag;
} /**
* (共享储存)存储Map类型的数据
* @author xiaowu
* @param filename
* @param map
* @return
*/
public boolean saveSharePreference(String filename, Map<String, Object> map) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
filename, Context.MODE_PRIVATE);
Editor editor = sharedPreferences.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 String) {
String s = (String) object;
editor.putString(key, s);
} else if (object instanceof Long) {
Long l = (Long) object;
editor.putLong(key, l);
}
}
return editor.commit();
} // 读文件权限最低,不需要传递文件操作模式
/**
* @author xiaowu
* @param fileName
* @return
*/
public Map<String,?> getSharePreference(String fileName){
Map<String,?> map = null;
SharedPreferences sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
map = sharedPreferences.getAll();
return map;
}
}

  Test类

  

 package com.example;

 import java.util.HashMap;
import java.util.Map; import android.test.AndroidTestCase;
import android.util.Log; import com.example.android_data_storage_share.perference.LoginService; /**
* @author xiaowu Note:必须继承AndroidTestCase这个class
*/
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 save2() {
LoginService service = new LoginService(getContext());
Map<String,Object> map = new HashMap<String, Object>();
map.put("name", "hw");
map.put("age", 12);
map.put("salary", 3000.0f);
map.put("id", 430381199007086018l);
map.put("isMan", true);
boolean flag = service.saveSharePreference("msg", map);
Log.i(TAG, "->>" + flag);
}
//取文件中的值
public void read(){
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("id"));
Log.i(TAG, "--->"+map.get("isMan"));
}
}

  

android 开发-数据存储之共享参数的更多相关文章

  1. 关于Android开发数据存储的方式(一)

    关于Android开发数据存储方式(一) 在厦门做Android开发也有两个月了,快情人节了.我还在弄代码. 在微信平台上开发自己的APP,用到了数据存储的知识,如今总结一下: 整体的来讲.数据存储方 ...

  2. Android数据存储之共享参数SharedPreferences

    SharedPreferences是Android的一个轻量级存储工具,采用的存储结构是Key-Value的键值对方式,类似于Java的Properties类,二者都是把Key-Value的键值对保存 ...

  3. Android开发--数据存储之File文件存储

    转载来自:http://blog.csdn.net/ahuier/article/details/10364757,并进行扩充 引言:Android开发中的数据存储方式 Android提供了5种方式存 ...

  4. android 开发-数据存储之文件存储

    android的文件存储是通过android的文件系统对数据进行临时的保存操作,并不是持久化数据,例如网络上下载某些图片.音频.视频文件等.如缓存文件将会在清理应用缓存的时候被清除,或者是应用卸载的时 ...

  5. Android开发--数据存储之数据库操作

    简介: SQLite 的介绍: SQLite数据库属于文本型的数据库,它是以文本的形式来保存的.Android提供了对 SQLite 数据库的完全支持,应用程序中的任何类都可以通过名称来访问任何的数据 ...

  6. Android开发数据存储之ContentProvider详解

    转载:十二.ContentProvider和Uri详解 一.使用ContentProvider(内容提供者)共享数据 ContentProvider在android中的作用是对外共享数据,也就是说你可 ...

  7. Android实现数据存储技术

    转载:Android实现数据存储技术 本文介绍Android中的5种数据存储方式. 数据存储在开发中是使用最频繁的,在这里主要介绍Android平台中实现数据存储的5种方式,分别是: 1 使用Shar ...

  8. Android中数据存储(四)——ContentProvider存储数据

    目录(?)[+]   当一个应用程序在Android中安装后,我们在使用应用的过程中会产生很多的数据,应用都有自己的数据,那么我们应该如何存储数据呢? 数据存储方式 Android 的数据存储有5种方 ...

  9. Android中数据存储(一)

    国庆没有给国家添堵,没有勾搭妹子,乖乖的写着自己的博客..... 本文将为大家介绍Android中数据存储的五种方式,数据存储可是非常重要的知识哦. 一,文件存储数据 ①在ROM存储数据 关于在ROM ...

随机推荐

  1. @JsonProperty 注解

    是Jackson注解.fastjson有可以用. 作用在字段或方法上,用来对属性的序列化/反序列化,可以用来避免遗漏属性,同时提供对属性名称重命名,比如在很多场景下Java对象的属性是按照规范的驼峰书 ...

  2. 使用JFileChooser保存文件

    --------------------siwuxie095                                 工程名:TestFileChooser 包名:com.siwuxie095 ...

  3. Flask05 cookie、类视图、方法视图、自己的404页面

    1 什么是cookie 就是网站存放到你浏览器中的一部分固定内容:当你下次访问我这个网站的时候,你会把之前我存放到你浏览器中的数据带回来给我        你要先登录(用户名.密码) ->   ...

  4. Struts2学习第四课 通过Aware接口获取WEB资源

    使用XxxAware接口 看代码: package logan.struts2.study; import java.util.Map; import org.apache.struts2.inter ...

  5. EIP权限工作流平台总结-4跨域配置

    1.预览地址:www.eipflow.com (1) 权限工作流:www.demo.eipflow.com/Account/Login (2) 基础权限版:www.auth.eipflow.com/A ...

  6. surging+EFCore 服务实现入门

    准备工作 本篇文章基于上篇基础上进行的,请先了解此篇  surging+CentOS7+docker+rancher2.0 菜鸟部署运行笔记 开发环境  Visual Studio 2017 15.5 ...

  7. <你的孤独,虽败犹荣> 很喜欢的句子

    希望未来的工作中能够经常出差,做一个能看到除了湖南之外的世界的人 即使我们一辈子给人打工,也要打自己愿意打的工 正在经历的孤独,我们称之为迷茫,经过的那些孤独,我们称之为成长 青春,是一个容量极其有限 ...

  8. es6实现类的多重继承

    1.类的多种继承,将多个类的接口“混入”(mix in)另一个类. function mix(...mixins) { class Mix { // 如果不需要拷贝实例属性下面这段代码可以去掉 // ...

  9. Codeforces 92C【二分】

    意: 求最少需要几个s1串拼接存在子串s2 (1≤|s1|≤1e4,1≤|s2|≤1e6). 思路(感谢ZQC): 每个字母的出现位置存个vector. 假设你当前已经用了A串的前x个字符,现在想要匹 ...

  10. Unity Shader着色器优化

    https://mp.weixin.qq.com/s?__biz=MzU5MjQ1NTEwOA==&mid=2247493518&idx=1&sn=c51b92e9300bcf ...