android 保存 用户名和密码 设置等应用信息优化
1、传统的保存用户名,密码方式 SharedPreferences
Editor editor = shareReference.edit();
editor.putString(KEY_NAME,"username_value");
通过这样的方法,能够基本满足需求,比如有用户名,那么就Editor.putString存放就好。
但是这样的方法有一些弊端:
(1)在存放一些集合信息,存储ArrayList就不合适
(2)如果针对用户,新增加了很多熟悉,比如性别,头像等信息,那么需要一个一个的添加put和get方法,非常的繁琐。
2、通过序列化对象,将对象序列化成base64编码的文本,然后再通过SharedPreferences 保存,那么就方便很多,只需要在对象里增加get和set方法就好。
3、 序列换通用方法, 将list对象或者普通的对象序列化成字符串
package com.example.imagedemo; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.List; import android.util.Base64; public class SerializableUtil { public static <E> String list2String(List<E> list) throws IOException{
//实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//然后将得到的字符数据装载到ObjectOutputStream
ObjectOutputStream oos = new ObjectOutputStream(baos);
//writeObject 方法负责写入特定类的对象的状态,以便相应的readObject可以还原它
oos.writeObject(list);
//最后,用Base64.encode将字节文件转换成Base64编码,并以String形式保存
String listString = new String(Base64.encode(baos.toByteArray(),Base64.DEFAULT));
//关闭oos
oos.close();
return listString;
} public static String obj2Str(Object obj)throws IOException
{
if(obj == null) {
return "";
}
//实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//然后将得到的字符数据装载到ObjectOutputStream
ObjectOutputStream oos = new ObjectOutputStream(baos);
//writeObject 方法负责写入特定类的对象的状态,以便相应的readObject可以还原它
oos.writeObject(obj);
//最后,用Base64.encode将字节文件转换成Base64编码,并以String形式保存
String listString = new String(Base64.encode(baos.toByteArray(),Base64.DEFAULT));
//关闭oos
oos.close();
return listString;
} //将序列化的数据还原成Object
public static Object str2Obj(String str) throws StreamCorruptedException,IOException{
byte[] mByte = Base64.decode(str.getBytes(),Base64.DEFAULT);
ByteArrayInputStream bais = new ByteArrayInputStream(mByte);
ObjectInputStream ois = new ObjectInputStream(bais); try {
return ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; } public static <E> List<E> string2List(String str) throws StreamCorruptedException,IOException{
byte[] mByte = Base64.decode(str.getBytes(),Base64.DEFAULT);
ByteArrayInputStream bais = new ByteArrayInputStream(mByte);
ObjectInputStream ois = new ObjectInputStream(bais);
List<E> stringList = null;
try {
stringList = (List<E>) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stringList;
} }
4、 要保存的用户对象
package com.example.imagedemo; import java.io.Serializable; import android.annotation.SuppressLint; public class UserEntity implements Serializable
{
private static final long serialVersionUID = -5683263669918171030L; private String userName;
// 原始密码 public String getUserName()
{
return userName;
} public void setUserName(String userName)
{
this.userName = userName;
} public String getPassword()
{
return password;
} public void setPassword(String password)
{
this.password = password;
} private String password; }
5、编写SharedPreUtil ,实现对对象的读取和保存
package com.example.imagedemo; import java.io.IOException;
import java.io.StreamCorruptedException; import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor; public class SharedPreUtil
{ // 用户名key
public final static String KEY_NAME = "KEY_NAME"; public final static String KEY_LEVEL = "KEY_LEVEL"; private static SharedPreUtil s_SharedPreUtil; private static UserEntity s_User = null; private SharedPreferences msp; // 初始化,一般在应用启动之后就要初始化
public static synchronized void initSharedPreference(Context context)
{
if (s_SharedPreUtil == null)
{
s_SharedPreUtil = new SharedPreUtil(context);
}
} /**
* 获取唯一的instance
*
* @return
*/
public static synchronized SharedPreUtil getInstance()
{
return s_SharedPreUtil;
} public SharedPreUtil(Context context)
{
msp = context.getSharedPreferences("SharedPreUtil",
Context.MODE_PRIVATE | Context.MODE_APPEND);
} public SharedPreferences getSharedPref()
{
return msp;
} public synchronized void putUser(UserEntity user)
{ Editor editor = msp.edit(); String str="";
try {
str = SerializableUtil.obj2Str(user);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
editor.putString(KEY_NAME,str);
editor.commit(); s_User = user;
} public synchronized UserEntity getUser()
{ if (s_User == null)
{
s_User = new UserEntity(); //获取序列化的数据
String str = msp.getString(SharedPreUtil.KEY_NAME, ""); try {
Object obj = SerializableUtil.str2Obj(str);
if(obj != null){
s_User = (UserEntity)obj;
} } catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return s_User;
} public synchronized void DeleteUser()
{
Editor editor = msp.edit();
editor.putString(KEY_NAME,""); editor.commit();
s_User = null;
} }
6、 调用Activity代码
package com.example.imagedemo; import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText; public class ActivityMain extends Activity
{ EditText edit_pwd;
EditText edit_name;
Button button; @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); SharedPreUtil.initSharedPreference(getApplicationContext()); edit_pwd = (EditText)findViewById(R.id.pwd);
edit_name = (EditText)findViewById(R.id.name); button = (Button)findViewById(R.id.btn); //保存到本地
button.setOnClickListener(new OnClickListener()
{ @Override
public void onClick(View v)
{ String name = edit_name.getText().toString();
String pwd = edit_pwd.getText().toString(); UserEntity user = new UserEntity();
user.setPassword(pwd);
user.setUserName(name); //用户名,密码保存在SharedPreferences
SharedPreUtil.getInstance().putUser(user);
}
});
Button delBtn = (Button)findViewById(R.id.btn_del);
delBtn.setOnClickListener(new OnClickListener()
{ @Override
public void onClick(View v)
{
SharedPreUtil.getInstance().DeleteUser();
edit_name.setText("");
edit_pwd.setText("");
}
}); UserEntity user = SharedPreUtil.getInstance().getUser();
if(!TextUtils.isEmpty(user.getPassword()) && !TextUtils.isEmpty( user.getUserName() ) ){
edit_name.setText(user.getUserName());
edit_pwd.setText(user.getPassword());
} } @Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
} }
对应的布局文件
<LinearLayout 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:orientation="vertical"
tools:context=".ActivityMain" > <EditText
android:id="@+id/name"
android:hint="please input name"
android:layout_width="fill_parent"
android:layout_height="40dip" /> <EditText
android:id="@+id/pwd"
android:layout_width="fill_parent"
android:hint="please input password"
android:layout_height="40dip" /> <Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="40dip"
android:text="保存" >
</Button> <Button
android:id="@+id/btn_del"
android:layout_width="wrap_content"
android:layout_height="40dip"
android:text="清除" >
</Button> </LinearLayout>
来个截图
7、 如果我们的应用程序有不太复杂的保存需求,那么就可借助 SerializableUtil list2String 将list对象保存为文本,然后在通过文本的方式来读取,这样就不用使用数据库了,会轻量很多。
android 保存 用户名和密码 设置等应用信息优化的更多相关文章
- Android简易实战教程--第十六话《SharedPreferences保存用户名和密码》
之前在Android简易实战教程--第七话<在内存中存储用户名和密码> 那里是把用户名和密码保存到了内存中,这一篇把用户名和密码保存至SharedPreferences文件.为了引起误导, ...
- 终于解决“Git Windows客户端保存用户名与密码”的问题(转载)
add by zhj:不建议用这种方法,建议用SSH,参见 TortoiseGit密钥的配置 http://www.cnblogs.com/ajianbeyourself/p/3817364.html ...
- iOS 使用Keychain 保存 用户名和密码到 本地
iOS 使用Keychain 保存 用户名和密码到 本地 之前曾把一些简单的数据保存在了plist,文件,及NsuserDefault里面, 但是如果要保存密码之类的,保存在本地就很不安全了: 但是利 ...
- git保存用户名和密码
git保存用户名和密码 简介:tortoiseGit(乌龟git)图形化了git,我们用起来很方便,但是我们拉取私有项目的时候,每次都要输入用户名和密码很麻烦,这里向大家介绍怎么避免多少输入 试验环境 ...
- Git Windows客户端保存用户名和密码
解决Git Windows客户端保存用户名和密码的方法,至于为什么,就不想说了. 1. 添加一个HOME环境变量,值为%USERPROFILE% 2. 开始菜单中,点击“运行”,输入“%Home%”并 ...
- TortoiseGit+msysgit保存用户名和密码
本文以windows系统为例 保存用户名和密码 在C盘的c:\Users**qing** (或可能是C:\Users\Administrator) (替换自己的用户名)找到.gitconfig, 如果 ...
- cookie保存用户名及密码
登陆页中,用户输入用户名密码,点击提交,后台对照mysq数据库中,看是否有对应的用户名,以及密码是否正确.如果正确 则将用户名密码分两份Cookie保存.页面跳转到登陆成功页. 用户再次访问登陆页时, ...
- Git Windows客户端保存用户名与密码
1. 在Windows中添加一个HOME环境变量,值为%USERPROFILE%,如下图: 2. 在“开始>运行”中打开%Home%,新建一个名为“_netrc”的文件. 3. 用记事本打开_n ...
- 终于解决“Git Windows客户端保存用户名与密码”的问题
这就是正确答案,我们已经验证过了,下面详细描述一下解决方法: 1. 在Windows中添加一个HOME环境变量,值为%USERPROFILE%,如下图: 2. 在“开始>运行”中打开%Home% ...
随机推荐
- [转]OOPC:Object-Oriented Programming in C
转载自:http://www.cnblogs.com/stli/archive/2010/10/16/1853190.html OOPC是指OOP(Object-Oriented Programmin ...
- PyAMF and django ForeignKey
In order to support this, PyAMF needs to provide a synonym mapping between fields. Until then, you c ...
- 关于js中的几个小问题。
问题1: 使用连续赋值后面的变量会成为全局对象的一个属性,并且这个属性可以通过delete删除. 原因:赋值语句是从右往左执行的,我们将10赋值给了c,但是c此时还声明,接着把c的返回值赋值给了b,但 ...
- 使用Service.Stack客户端编写redis pub sub的方法
pub相对简单 client.PublishMessage("channel", "msg"); sub有2种方法 方法1 var subscription ...
- LeetCode——Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...
- 使用Spark分析拉勾网招聘信息(一):准备工作
本系列专属github地址:https://github.com/ios122/spark_lagou 前言 我觉得如果动笔,就应该努力地把要说的东西表达清楚.今后一段时间,尝试下系列博客文章.简单说 ...
- [阅读]个人阅读作业week7
People-oriented in Agile People-oriented in Agile One Leader Prepare Good ideas from users People-or ...
- Spring基础—— 泛型依赖注入
一.为了更加快捷的开发,为了更少的配置,特别是针对 Web 环境的开发,从 Spring 4.0 之后,Spring 引入了 泛型依赖注入. 二.泛型依赖注入:子类之间的依赖关系由其父类泛型以及父类之 ...
- Linq之group子句
在Linq查询语句中,group子句主要作用是对查询的结果集进行分组.并返回元素类型为IGrouping<TKey,TElement>的对象序列. 下面我们在代码实例中创建一个GroupQ ...
- MVC视图展现模式之移动布局
参考:http://www.cnblogs.com/dunitian/p/5218140.html 简单点,直接上用法 新建MVC项目,在golbal.asax中添加如下代码 //添加一个自定义后缀 ...