您的位置:首页 > 移动开发 > Android开发

Android学习笔记033之数据存储—SharedPreference

2016-07-20 15:30 447 查看
  在上一篇中,我们介绍了Android实现文件存储数据的方式,这一篇我们介绍Android的另外一种存储数据的方式——sharedPreference存储数据。SharedPreference存储是一种轻量级的存储,多用于保存比较简单的数据,比如用户是否登录、保存用户的登录名和登录密码等。Sharedpreference存储数据是通过XML的形式,类似于Map集合,键值对的形式,是Android中保存数据最简单的一种,所有的逻辑主要依靠三个类:Sharedpreference、SharedPreferences.Editor、SharedPreferences.OnSharedPreferenceChangeListener。下面我们来学习一下这种存储数据的方式:

1、SharedPreference使用简单实例

  SharedPreference存储数据的步骤:

1、使用Context.getSharedPreference()获取到SharedPreference对象。getSharedPreference()中有两个参数,第一个是保存的文件名,第二个是保存的模式,与上一篇中介绍的文件操作模式类似,不过使用的时候需要在前面加上Context

2、根据上一步中获取到的SharedPreference对象调用edit()方法获取Edit对象

3、获取到Edit对象之后调用putXX()方法保存数据,是键值对的形式

4、将数据保存之后,Edit对象调用commit()方法提交数据

  SharedPreference读取数据的步骤:

1、第一步与存储数据的第一步一样,都是获取到SharedPreference对象

2、第二步就直接通过获取到的SharedPreference对象,调用getXXX()方法读取数据

上面简单讲述了SharedPreference存储和读取数据的步骤,下面我们通过一个小例子实现SharedPreference存储和读取数据,体会一下:

首先是Activity代码:

private EditText et_sp_name;
private EditText et_sp_pass;
private Button btn_sp_commit;
private SharedPreferences mPreferences;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sp);
et_sp_name= (EditText) findViewById(R.id.et_sp_name);
et_sp_pass= (EditText) findViewById(R.id.et_sp_pass);
btn_sp_commit= (Button) findViewById(R.id.btn_sp_commit);
//初始化,获取到Sharedpreference对象
mPreferences= this.getSharedPreferences("sp_test",Context.MODE_PRIVATE);

et_sp_name.setText(mPreferences.getString("sp_name",""));
et_sp_pass.setText(mPreferences.getString("sp_pass",""));

btn_sp_commit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//获取到Edit对象
SharedPreferences.Editor editor=mPreferences.edit();
//保存数据
editor.putString("sp_name",et_sp_name.getText().toString());
editor.putString("sp_pass",et_sp_pass.getText().toString());
//调用commit()方法,必须要调用,不然不会写入数据
editor.commit();
ToastUtils.showToast(SPActivity.this,"数据已经成功保存");
}
});
}


然后是布局文件代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="14dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/et_sp_name"
android:textSize="14sp"
android:hint="请输入用户名"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/et_sp_pass"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:hint="请输入密码"
/>
<Button
android:id="@+id/btn_sp_commit"
android:text="提交"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

</LinearLayout>


实现效果图:



这样就可以实现SharedPreference进行数据的保存和读取,比较简单。

2、SharedPreference跨应用读取数据

  SharedPreference跨应用读取数据的步骤如下:

1、通过包名获取到相应应用的Context,需要捕获PackageManager.NameNotFoundException异常

2、通过Context调用getSharedPreference()方法获取到Sharedpreference对象,getSharedPreference()方法里面的参数必须跟想要获取数据的应用一样,还有操作模式不能为私有

3、用上一步获取到的Sharedpreference对象调用getXXX()方法获取数据

这里比较简单,就不在写例子了。

3、SharedPreference加密保存数据

  手机在没有ROOT的情况下,别人很难获取到包名,但是ROOT之后,会比较容易获取到包名,这样别人容易获取到我们应用保存的用户数据,所以我们需要对我们保存的数据进行加密,这里就简单实现MD5加密。

网上MD5加密的工具类很多,下面是一个:

package com.example.datasave;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
* 提取文件MD5值
*
*/
public class MD5Utils {
private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

private static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
sb.append(HEX_DIGITS[b[i] & 0x0f]);
}
return sb.toString();
}

/**
* 文件加密
*
* @param filename
* @return
*/
public static String md5file(String filename) {
InputStream fis;
byte[] buffer = new byte[1024];
int numRead = 0;
MessageDigest md5;
try {
fis = new FileInputStream(filename);
md5 = MessageDigest.getInstance("MD5");
while ((numRead = fis.read(buffer)) > 0) {
md5.update(buffer, 0, numRead);
}
fis.close();
return toHexString(md5.digest());
} catch (Exception e) {
System.out.println("error");
return null;
}
}

/**
* 字符串加密
*
* @param string
* @return
*/
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(
string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}

StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10)
hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}

}


使用MD5加密保存数据直接就是将数据经过MD5转换之后,通过SharedPreference保存,这里就 不在做实现了,跟保存数据差不多。

4、SharedPreference工具类

最后提供一个SharedPreference的工具类:

package com.example.datasave;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.Map;
import java.util.Set;

/**
* Created by Devin on 2016/7/20.
*/
public class SharePreferenceUtil {
private static SharedPreferences mSharedPreferences;

public static final String SP_FILE_NAME="sp_file_name";

/**
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
*
* @param context
* @param key
*            键值对的key
* @param value
*            键值对的值
* @return 是否保存成功
*/
public static boolean setValue(Context context, String key, Object value) {
if (mSharedPreferences == null) {
mSharedPreferences = context.getSharedPreferences(SP_FILE_NAME,Context.MODE_PRIVATE);
}

SharedPreferences.Editor edit = mSharedPreferences.edit();
if (value instanceof String) {
return edit.putString(key, (String) value).commit();
} else if (value instanceof Boolean) {
return edit.putBoolean(key, (Boolean) value).commit();
} else if (value instanceof Float) {
return edit.putFloat(key, (Float) value).commit();
} else if (value instanceof Integer) {
return edit.putInt(key, (Integer) value).commit();
} else if (value instanceof Long) {
return edit.putLong(key, (Long) value).commit();
} else if (value instanceof Set) {
new IllegalArgumentException("Value can not be Set object!");
return false;
}
return false;
}

/**
* 得到Boolean类型的值
*
* @param context
* @param key
* @param defaultValue
* @return
*/
public static boolean getBoolean(Context context, String key,
boolean defaultValue) {
if (mSharedPreferences == null) {
mSharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
}
return mSharedPreferences.getBoolean(key, defaultValue);
}

/**
* 得到String类型的值
*
* @param context
* @param key
* @param defaultValue
* @return
*/
public static String getString(Context context, String key,
String defaultValue) {
if (mSharedPreferences == null) {
mSharedPreferences = context.getSharedPreferences(SP_FILE_NAME,Context.MODE_PRIVATE);
}
return mSharedPreferences.getString(key, defaultValue);
}

/**
* 得到Float类型的值
*
* @param context
* @param key
* @param defaultValue
* @return
*/
public static Float getFloat(Context context, String key, float defaultValue) {
if (mSharedPreferences == null) {
mSharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
}
return mSharedPreferences.getFloat(key, defaultValue);
}

/**
* 得到Int类型的值
*
* @param context
* @param key
* @param defaultValue
* @return
*/
public static int getInt(Context context, String key, int defaultValue) {
if (mSharedPreferences == null) {
mSharedPreferences = context.getSharedPreferences(SP_FILE_NAME,Context.MODE_PRIVATE);
}
return mSharedPreferences.getInt(key, defaultValue);
}

/**
* 得到Long类型的值
*
* @param context
* @param key
* @param defaultValue
* @return
*/
public static long getLong(Context context, String key, long defaultValue) {
if (mSharedPreferences == null) {
mSharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
}
return mSharedPreferences.getLong(key, defaultValue);
}

/**
* 移除某个key值已经对应的值
*
* @param context
* @param key
*/
public static boolean remove(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
return editor.commit();
}

/**
* 清除所有数据
*
* @param context
* @return 是否成功
*/
public static boolean clear(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
return editor.commit();
}

/**
* 查询某个key是否已经存在
*
* @param context
* @param key
* @return 是否存在
*/
public static boolean contains(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences( SP_FILE_NAME, Context.MODE_PRIVATE);
boolean result = sp.contains(key);

return result;
}

/**
* 返回所有的键值对
*
* @param context
* @return Map<String, ?>
*/
public static Map<String, ?> getAll(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
return sp.getAll();
}
}


  关于SharedPreference存储数据就介绍到这里,下一篇我们会介绍SQLite数据库保存数据。

附上SharedPreference的国内镜像API
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: