[转载]Android用户登录数据存储的三种方式 – bibei1234 – 博客园.
登录的页面:
布局代码:
<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:orientation=“vertical” >
<!– 用户名的布局 –>
<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content” >
<TextView
android:id=“@+id/view_name”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“@string/text_name” />
<EditText
android:id=“@+id/edit_name”
android:layout_width=“0dp”
android:layout_height=“wrap_content”
android:layout_weight=“1”
android:ems=“10”
android:inputType=“textPersonName” >
<requestFocus />
</EditText>
</LinearLayout>
<!– 密码布局 –>
<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content” >
<TextView
android:id=“@+id/view_pass”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“@string/text_pass” />
<EditText
android:id=“@+id/edit_pass”
android:layout_width=“0dp”
android:layout_height=“wrap_content”
android:layout_weight=“1”
android:ems=“10”
android:inputType=“textPassword” >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content” >
<Button
android:id=“@+id/btn_login”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginLeft=“0dp”
android:text=“@string/text_login” />
<CheckBox
android:id=“@+id/cbx_rember”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginLeft=“100dp”
android:text=“@string/text_rember” />
</LinearLayout>
<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content” >
<RadioGroup
android:id=“@+id/rg”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:orientation=“horizontal”
tools:ignore=“UselessParent” >
<RadioButton
android:id=“@+id/radio_rom”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:checked=“true”
android:text=“@string/rom” />
<RadioButton
android:id=“@+id/radio_sp”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“@string/sp” />
<RadioButton
android:id=“@+id/radio_sd”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“@string/sd” />
</RadioGroup>
</LinearLayout>
</LinearLayout>
String。Xml的值里面的代码:
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<string name=“app_name”>用户登录三种数据存储方式</string>
<string name=“action_settings”>Settings</string>
<string name=“hello_world”>Hello world!</string>
<string name=“text_name”>用户名:</string>
<string name=“text_pass”>密码:</string>
<string name=“text_login”>登陆</string>
<string name=“text_rember”>记住密码</string>
<string name=“rom”>rom存储</string>
<string name=“sp”>sp存储</string>
<string name=“sd”>sd存储</string>
</resources>
FileService 服务层的代码:
package www.csdn.net.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import www.csdn.net.tools.StreamTools;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.widget.Toast;
public class FileService {
// 上下文的对象
public Context context;
public FileService(Context context) {
this.context = context;
}
/**
* 往手机内存上存储用户名与密码的操作
*
* @param name
* @param pass
* @param fileName
* @return
* @throws IOException
*/
public boolean saveToRom(String name, String pass, String fileName)
throws IOException {
try {
// 通过openFileOutput()方法获取一个文件的输出流对象
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_PRIVATE);
// 拼接用户名与密码
String result = name + “:” + pass;
fos.write(result.getBytes());
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 追加模式
*
* @param name
* @param pass
* @param fileName
* @return
*/
public boolean saveToRomAppend(String name, String pass, String fileName) {
// MODE_PRIVATE :私有的模式
// 为默认操作模式
try {
// 通过openFileOutput()方法获取一个文件的输出流对象
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_APPEND);
// 拼接用户名与密码
String result = name + “:” + pass;
// 写入
fos.write(result.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 可读模式
*
* @param name
* @param pass
* @param fileName
* @return
*/
public boolean saveToRomReadable(String name, String pass, String fileName) {
// MODE_PRIVATE :私有的模式
// 为默认操作模式
try {
// 通过openFileOutput()方法获取一个文件的输出流对象
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_WORLD_READABLE);
// 拼接用户名与密码
String result = name + “:” + pass;
// 写入
fos.write(result.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 可以写的模式
*
* @param name
* @param pass
* @param fileName
* @return
*/
public boolean saveToRomWritable(String name, String pass, String fileName) {
// MODE_PRIVATE :私有的模式
// 为默认操作模式
try {
// 通过openFileOutput()方法获取一个文件的输出流对象
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_WORLD_WRITEABLE);
// 拼接用户名与密码
String result = name + “:” + pass;
// 写入
fos.write(result.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// 读取数据
public Map<String, String> readFile(String fileName) throws IOException {
Map<String, String> map = null;// new HashMap<String, String>();
try {
FileInputStream fis = context.openFileInput(fileName);
String value = StreamTools.getValue(fis);
String values[] = value.split(“:”);
// 判断map集合
if (values.length > 0) {
map = new HashMap<String, String>();
map.put(“name”, values[0]);
map.put(“pass”, values[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return map;
}
/**
* 采用SharedPreferences存储数据的操作
*
* @param name
* @param pass
* @param fileName
* @return
*/
public boolean saveBytsp(String name, String pass, String fileName) {
// 通过上下文获取Sharepreferences对象
SharedPreferences preferences = context.getSharedPreferences(fileName,
context.MODE_PRIVATE);
// 返回Editor对象
Editor editor = preferences.edit();
editor.putString(“name”, name);
editor.putString(“pass”, pass);
editor.putInt(“age”, 8);
editor.putBoolean(“flag”, true);
// 提交
return editor.commit();
}
public boolean saveToSDCard(String name, String pass, String fileName) {
// 首先判断是否拥有SDcard
if (Environment.getExternalStorageDirectory().equals(
Environment.MEDIA_MOUNTED)) {
// SDCard写入数据
// 首先要获取SDCard目录
File sdCardDir = Environment.getExternalStorageDirectory();
File file = new File(sdCardDir, fileName);// 根据目录及创建文件的名称 创建文件
try {
FileOutputStream fos = new FileOutputStream(file);
String result = name + “:” + pass;
fos.write(result.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
} else {
Toast.makeText(context, “手机不拥有SDCard”, Toast.LENGTH_LONG).show();
}
return true;
}
// 读取数据
public Map<String, String> readFileSDcard(String fileName) {
Map<String, String> map = null;// new HashMap<String, String>();
try {
// 第一步:获取SDcard目录文件
File sdcardDir = Environment.getExternalStorageDirectory();
// 第二步:根据sdcard目录及文件名称 创建文件对象
File file = new File(sdcardDir, fileName);
// 第三步:根据文件对象创建文件的输入流
FileInputStream fis = new FileInputStream(file);
// 第四步:利用StreamTools工具 获取文件中的内容
String value = StreamTools.getValue(fis);
// 根据规则拆分
String values[] = value.split(“:”);
//
if (values.length > 0) {
map = new HashMap<String, String>();
map.put(“name”, values[0]);
map.put(“pass”, values[1]);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
这里用到的一个工具:
package www.csdn.net.tools;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class StreamTools {
public static String getValue(FileInputStream fis) throws IOException{
//字节的输出流对象
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte [] buffer = new byte[1024];
int length=1;
while ((length = fis.read(buffer)) != -1) {
stream.write(buffer, 0, length);
}
stream.flush();
stream.close();
String value= stream.toString();
return value;
}
}
最主要的代码: Activity
package com.example.file;
import java.io.IOException;
import java.util.Map;
import www.csdn.net.service.FileService;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class LoginActivity extends Activity {
// 声明 获取的用户名与密码的组件
public EditText edit_name, edit_pass;
// 声明登陆按钮对象
public Button btn_login;
// 声明CheckBox组件对象
public CheckBox box_remember;
//创建业务对象
public FileService fileService;
// 声明出单选的组件
public RadioButton radio_rom, radio_sp, radio_sd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置显示视图
setContentView(R.layout.activity_login);
//实例化业务对象
fileService = new FileService(this);
// 根据id名称获取相应组件对象
edit_name = (EditText) findViewById(R.id.edit_name);
edit_pass = (EditText) findViewById(R.id.edit_pass);
btn_login = (Button) findViewById(R.id.btn_login);
box_remember = (CheckBox) findViewById(R.id.cbx_rember);
// 给按钮注册事件
btn_login.setOnClickListener(new MyOnClickListener());
radio_rom = (RadioButton) findViewById(R.id.radio_rom);
radio_sp = (RadioButton) findViewById(R.id.radio_sp);
radio_sd = (RadioButton) findViewById(R.id.radio_sd);
// 采用SharedPreferences实现数据回显
// 根据上下文的api获取SharedPreferences对象
/*
SharedPreferences preferences =
this.getSharedPreferences(“li”,Context.MODE_PRIVATE);
edit_name.setText(preferences.getString(“name”, “csdn”));
edit_pass.setText(preferences.getString(“pass”, “csdn”));
*/
// 采用sdcard数据进行实现数据回显
// 获取map集合对象
//回显数据
Map<String, String> map = fileService.readFileSDcard(“csdnsdcard.txt”);
if(map!=null){
edit_name.setText(map.get(“name”));
edit_pass.setText(map.get(“pass”));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
// 内部类
class MyOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_login:
// 获取用户名与密码
String name = edit_name.getText().toString();
String pass = edit_pass.getText().toString();
// 判断用户名与密码是否为空
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)) {
Toast.makeText(LoginActivity.this, “用户名或者密码不能为空“,
Toast.LENGTH_LONG).show();
return;
} else {
// 首先 判断 是否记住密码
if (box_remember.isChecked()) {
// 判断采用什么方式保存
if (radio_rom.isChecked()) {
// 采用rom保存
} else if (radio_sp.isChecked()) {
// 采用SharedPreferences
boolean flag = fileService.saveBytsp(name, pass,
“csdn”);
if (flag) {
Toast.makeText(LoginActivity.this, “保存成功“,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, “保存失败“,
Toast.LENGTH_LONG).show();
}
} else if (radio_sd.isChecked()) {
// sd卡保存
boolean flag = fileService.saveToSDCard(name, pass,
“csdnsdcard.txt”);
if (flag) {
Toast.makeText(LoginActivity.this, “保存成功“,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, “保存失败“,
Toast.LENGTH_LONG).show();
}
}
}
}
break;
default:
break;
}
}
}
}
在进行sdcard存储的时候要有权限:
<uses-sdk
android:minSdkVersion=“8”
android:targetSdkVersion=“17” />
<!– 创建与删除文件的权限 –>
<uses-permission android:name=“android.permission.MOUNT_UNMOUNT_FILESYSTEMS”/>
<!– 写入数据的权限 –>
<uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE”/>
存放的数据在/data/data/<package name>/files目录应用私有的文件,以txt的形式显示。
最后的效果图:
使用文件进行数据存储
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
如果希望文件被其他应用读和写,可以传入:
openFileOutput(“itcast.txt”, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
android有一套自己的安全模型,当应用程序(.apk)在安装时系统就会分配给他一个userid,当该应用要去访问其他资源比如文件的时候,就需 要userid匹配。默认情况下,任何应用创建的文件,sharedpreferences,数据库都应该是私有的(位于/data/data /<package name>/files),其他程序无法访问。除非在创建时指定了Context.MODE_WORLD_READABLE或者 Context.MODE_WORLD_WRITEABLE ,只有这样其他程序才能正确访问。
读取文件内容
如果要打开存放在/data/data/<package name>/files目录应用私有的文件,可以使用Activity提供openFileInput()方法。
FileInputStream inStream = this.getContext().openFileInput(“itcast.txt”);
Log.i(“FileTest”, readInStream(inStream));
readInStream()的方法请看本页下面备注。
或者直接使用文件的绝对路径:
File file = new File(“/data/data/cn.itcast.action/files/itcast.txt”);
FileInputStream inStream = new FileInputStream(file);
Log.i(“FileTest”, readInStream(inStream));
注意:上面文件路径中的“cn.itcast.action”为应用所在包,当你在编写代码时应替换为你自己应用使用的包。
对于私有文件只能被创建该文件的应用访问,如果希望文件能被其他应用读和写,可以在创建文件时,指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。
Activity还提供了getCacheDir()和getFilesDir()方法:
getCacheDir()方法用于获取/data/data/<package name>/cache目录
getFilesDir()方法用于获取/data/data/<package name>/files目录