赞
踩
Android系统中主要提供了三种方式用于简单地实现数据持久化功能,即文件存储、SharedPreference存储及数据库存储。
(一)文件存储
文件存储不对存储的内容进行任何的格式化处理,所有数据都是原封不动地保存在文件中,所以比较适用于存储一些简单的文本数据或二进制数据。
如何将数据存储到文件中:
String fileName = et1.getText().toString();
String fileContent = et2.getText().toString();
try {
FileOutputStream fileOutputStream = openFileOutput(fileName,Context.MODE_PRIVATE);
//UTF-8是基于Linux的编码,gb2312是基于window的编码
fileOutputStream.write(fileContent.getBytes("UTF-8"));
fileOutputStream.close();
Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
如何从文件中读取数据:
String fileName = et1.getText().toString();
try {
FileInputStream fileInputStream = openFileInput(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String msg = "";
StringBuffer buffer = new StringBuffer();
while((msg = bufferedReader.readLine()) != null){
buffer.append(msg);
}
tv.setText(buffer);
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
存储到SD卡中(极少用):
public void showSD(View view){
//判断有没有SD卡
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String fileName = et1.getText().toString();
String fileContent = et2.getText().toString();
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
try {
FileOutputStream fileOutputStream = new FileOutputStream(path +"/"+fileName);
fileOutputStream.write(fileContent.getBytes("UTF-8"));
fileOutputStream.close();
Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.i("MainActivity",e.toString());
e.printStackTrace();
}
}else {
Toast.makeText(this,"SD卡不可用",Toast.LENGTH_SHORT).show();
}
}
从SD卡里面读取数据
public void readSD(View view){
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String fileName = et1.getText().toString();
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
try {
FileInputStream fileInputStream = new FileInputStream(path +"/"+fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String msg = "";
StringBuffer buffer = new StringBuffer();
while((msg = bufferedReader.readLine()) != null){
buffer.append(msg);
}
tv.setText(buffer);
} catch (Exception e) {
e.printStackTrace();
}
}else {
Toast.makeText(this,"SD卡不可用",Toast.LENGTH_SHORT).show();
}
}
(二)、SharedPreferences是使用键值对的方式来存储,支持多种不同的数据类型存储。
使用SharedPreferences存储数据,需先获取到SharedPreferences对象,以下有三种方法:
1、Context类中的getSharedPreences()方法
2、Activity类中的getPreferences()方法
3、PreferenceManager类中的getDefaultSharedPreferences()方法
获得SharedPreferences对象之后,向SharedPreferences文件中存储数据,主要分以下三步实现:
1、调用SharedPreferences对象的edit()方法获取一个SharedPreferences.Editor对象;
2、向SharedPreferences.Editor对象添加数据;
3、调用commit()方法将添加的数据提交,从而完成数据存储操作
public class MainActivity extends Activity {
private EditText et;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.et);
sharedPreferences = getSharedPreferences("info", MODE_PRIVATE);
}
public void show(View view) {
Editor edit = sharedPreferences.edit();
String pwd =et.getText().toString();
edit.putString("pwd",pwd);
edit.commit();
}
public void read(View view){
String pwd = sharedPreferences.getString("pwd",null);
et.setText(pwd);
}
}
(三)、SQLite数据库存储
前两种只适用于保存简单的数据和键值对,当需要保存大量复杂的关系数据的时候,需用到SQLite。SQLite是一款轻量级的关系型数据库,运算快,占用资源少,适合在移动设备上适用。
1、适用SQL语句操作数据库:
private SQLiteDatabase db;
db = SQLiteDatabase.openOrCreateDatabase(getFilesDir() + "/info.db", null);
public void save(View view) {
String userName = userName_et.getText().toString();
String pwd = pwd_et.getText().toString();
//若数据库中存在表,则执行insert(userName, pwd);反之,抛出异常,执行create()和insert(userName, pwd)
try {
insert(userName, pwd);
} catch (Exception e) {
create();
insert(userName, pwd);
}
}
/**
* 建表操作
*/
private void create() {
String createsql = "create table user(_id integer primary key autoincrement,username,password)";
db.execSQL(createsql);
}
/**
* 插入
* @param userName
* @param pwd
*/
private void insert(String userName,String pwd) {
Log.i("MainActivity","insert");
String insertsql = "insert into user(username,password) values(?,?)";
db.execSQL(insertsql, new String[]{userName,pwd});
Toast.makeText(this,"插入成功",Toast.LENGTH_SHORT).show();
userName_et.setText("");
pwd_et.setText("");
}
/**
* 查询
* @return
*/
private Cursor select(){
String selectsql = "select * from user";
Cursor cursor = db.rawQuery(selectsql,null);
return cursor;
}
/**
* 删除
* @param id
*/
public void delete(String id){
String deletesql = "delete from user where _id = ?";
db.execSQL(deletesql, new String[]{id});
}
/**
* 修改
*/
public void update(String name,String pwd){
String updatasql = "update user set password = ? where username = ?";
db.execSQL(updatasql, new String[]{pwd,name});
}
2、借助SQLiteOpenHelper,由于SQLiteOpenHelper是抽象类,所以需创建一个自己的帮助类去继承它。
public class MyOpendhelper extends SQLiteOpenHelper{
public MyOpendhelper(Context context) {
//第二个参数是数据库名
//第三个参数是允许我们在查询数据的时候返回一个自定义的Cursor,一般传入null
//第四个参数表示当前数据库的版本号
super(context,"info.db",null,1);
}
//用于创建数据库
@Override
public void onCreate(SQLiteDatabase db) {
String createsql = "create table user(_id integer primary key autoincrement,username,password)";
db.execSQL(createsql);
}
//用于对数据库的升级
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public class MainActivity extends Activity {
private EditText userName_et, pwd_et;
private SQLiteDatabase db;
private ListView listView;
private MyOpendhelper myOpendhelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userName_et = (EditText) findViewById(R.id.username_et);
pwd_et = (EditText) findViewById(R.id.pwd_et);
listView = (ListView) findViewById(R.id.lv);
myOpendhelper = new MyOpendhelper(this);
//获取一个能读写的数据库
db = myOpendhelper.getWritableDatabase();
//delete();
update();
}
public void save(View view){
String name = userName_et.getText().toString();
String pwd = pwd_et.getText().toString();
insert(name,pwd);
}
public void read(View view){
select();
}
private void insert(String userName,String password){
ContentValues values = new ContentValues();
values.put("username",userName);
values.put("password", password);
db.insert("user", null, values);
Toast.makeText(this,"插入成功",Toast.LENGTH_SHORT).show();
userName_et.setText("");
pwd_et.setText("");
}
private void delete(){
db.delete("user","_id = ?", new String[]{"1"});
}
private void update(){
ContentValues values = new ContentValues();
values.put("password","0000000");
db.update("user", values,"username = ?", new String[]{"briup"});
}
private void select(){
Cursor cursor = db.query("user",new String[]{"username","password"},"_id between ? and ?",new String[]{"1","10"},
null, null, "_id desc", null);
while(cursor.moveToNext()){
Log.i("tag",cursor.getString(0));
Log.i("tag", cursor.getString(1));
}
}
}
SQLiteOpenHelper的两个实例方法:getReadableDatabase()和getWriteableDatabase()都可以创建或打开一个现有的数据库,并返回一个可对数据库进行读写操作的对象,不同的是,当数据库不可写入的时候(如磁盘空间已满)getWriteableDatabase()出现异常,而getReadableDatabase()方法取得实例是先调用getWriteableDatabase(),如数据库的磁盘已满,此时返回打开失败,继而用getWriteableDatabase的实例以只读方式去打开数据库。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。