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. nginx做代理部署WordPress

    实验环境:CentOS7 服务器172.16.252.142做Nginx代理服务器: [root@conf.d localhost]#iptables -F [root@conf.d localhos ...

  2. GIF助手激活教程(购买+激活)图文版

    GIF助手首页==>设置(右上角) ==>输入激活码会弹出购买或者激活的对话框.(如果不明白操作,可以点击如何购买激活码先查看购买帮助指南再进行购买) 点击复制设备码并购买. 此时会进入到 ...

  3. UI线程中非安全操作与安全操作

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

  4. Flask15 远程开发环境搭建、安装虚拟机、导入镜像文件、创建开发环境、pycharm和远程开发环境协同工作

    1 安装VM虚拟机 待更新... 2 导入镜像文件 待更新... 3 启动虚拟机 4 远程连接虚拟机 4.1 安装xShell软件 待更新... 4.2 创建一个新的连接 4.2.1 在虚拟机中获取虚 ...

  5. JavaEE资源

    JavaEE资源   http://bbs.itheima.com/forum.php?mod=forumdisplay&fid=183

  6. 20169219《linux内核原理与分析》第六周作业

    网易云课堂学习 1.intel x86 CPU有四种不同的执行级别0-3,linux只使用了其中的0级和3级分贝来表示内核态和用户态. 2.一般来说在linux中,地址空间是一个显著的标志:0xc00 ...

  7. SCUT - 321 - Tobby's magic - 线段树

    https://scut.online/p/321 第一次做区间线段树. 感觉和单点的一样啊.pushdown的时候要注意一些问题,st的值有可能是跟区间长度有关的. #include<bits ...

  8. python 关于时区

    pytz提供了时区对象timezone 如果我们如此使用: tz = pytz.timezone('Asia/Shanghai') datetime.datetime(nYear, nMonth, n ...

  9. [JLOI2012]树 倍增优化

    题目描述 在这个问题中,给定一个值S和一棵树.在树的每个节点有一个正整数,问有多少条路径的节点总和达到S.路径中节点的深度必须是升序的.假设节点1是根节点,根的深度是0,它的儿子节点的深度为1.路径不 ...

  10. [題解](迭代加深)POJ2248_Addition Chains

    發現m不會特別大,也就是層數比較淺,所以採用迭代加深 由於xi+xj可能相同,所以開一下vis數組判斷重複 #include<iostream> #include<cstdio> ...