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. Velocity常用标签的讲解

    Velocity是一个基于java的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象. 当Veloci ...

  2. 愚人的linux内核2440移植札记(超曲折版)

    http://blog.csdn.net/dreambegin/article/details/6904822 原来文章叫--编译内核之初体验.后来想了想,这篇文章让我体验了好多遍.不该叫这么大气的名 ...

  3. openStack kvm 虚拟机CPU颗粒化控制

    前一篇理解cpu topology对CPU Topology进行了学习总结,这里想总结下OpenStack下vCPU与pCPU常用的的绑定方式. 在尝试这些绑定之前,尤其是处理NUMA架构时还是建议看 ...

  4. Java探索之旅(4)——方法和Random&Math类

    1.基本知识点    ❶方法在C++里面称为函数.调用方法时,应该类型兼容--即不需显式类型转换即可将形参传递给实参.    ❷形参的改变不影响实参的值.    ❸Java注重模块化设计和自顶向下的设 ...

  5. javascript深入理解js闭包(转)

    javascript深入理解js闭包 转载  2010-07-03   作者:    我要评论 闭包(closure)是Javascript语言的一个难点,也是它的特色,很多高级应用都要依靠闭包实现. ...

  6. Spring的概况

    ----------------siwuxie095 Spring 的简介 Spring 是一个轻量级 控制反转(IoC) 和 面向切面(AOP) 的容器框架 年,它是为了解决企业应用开发的复杂性而诞 ...

  7. Spring 框架学习整理

    JDBC操作数据库的基本入门中存在什么问题? *   导致驱动注册两次是个问题,但不是严重的. *   严重的问题:是当前类和mysql的驱动类有很强的依赖关系. *      当我们没有驱动类的时候 ...

  8. mahout过滤推荐结果 Recommender.recommend(long userID, int howMany, IDRescorer rescorer)

    Recommender.recommend(uid, RECOMMENDER_NUM, rescorer); Recommender.recommend(long userID, int howMan ...

  9. netty的引用计数

    netty的引用计数文档看http://netty.io/wiki/reference-counted-objects.html 为什么会引用引用计数呢,Java中不是有gc线程帮我们回收对象吗?我个 ...

  10. 17. PHP+Mysql注入防护与绕过

    黑名单关键字过滤与绕过 过滤关键字and.or PHP匹配函数代码如下: preg_match('/(and|or)/i', $id) 如何Bypass,过滤注入测试语句: 1 or 1 = 1   ...