文件存储:
- android的文件存储用的是java IO流那一套,所以这里先简单地总结一下java IO的一些重要知识点。
- IO流分为两大类,字节流和字符流,它们之间的桥梁是outputStreamWriter和inputStreamReader。
- 字节流,处理一些二进制编码的文件,比如MP3,音频文件的读取和写入用字节流处理会方便一些。为了能够提高读写效率,一次性把数据写、读。我们采用DataOutputStream。针对file的写、读,我们使用DataOutputStream装饰FileOutputStream;针对byte的写读,我们使用DataOutputStream装饰ByteArrayOutputStream。
- 字符流,方便处理字符编码的文件。
- 由于android中,Context类中提供了一个openFIleOutput()方法,返回一个FileOutputStream对象。此方法有两个参数,第一个参数是指定文件名,第二个参数是指定文件的操作模式,MODE_PRIVATE(默认的操作模式,覆盖原文件的内容),MODE_APPEND(往文件追加内容,不存在就创建新的文件)。
private void load() {
BufferedReader in=null;
StringBuilder content=new StringBuilder();
try {
in=new BufferedReader(new InputStreamReader(openFileInput("data")));
String text="";
while ((text=in.readLine())!=null){
content.append(text);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
edit.setText(content);
}
}
}
SharedPreferences存储
SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)SharedPreferences常用来存储一些轻量级的数据。
- 得到SharedPreferences的对象实例
- 在Context类中的getSharedPreferences()方法
- 在Activity类中的getPreference()方法
- PreferenceManager类中的getDefaultSharedPreferences()静态方法。
- 获得SharedPreference.Editor对象,通过SharedPreference对象的edit()方法
- 向Editor对象添加数据
- 调用commit()方法将添加的数据提交。
//实例化SharedPreferences对象(第一步)
SharedPreferences mySharedPreferences= getSharedPreferences("test",
Activity.MODE_PRIVATE);
//实例化SharedPreferences.Editor对象(第二步)
SharedPreferences.Editor editor = mySharedPreferences.edit();
//用putString的方法保存数据
editor.putString("name", "Karl");
editor.putString("habit", "sleep");
//提交当前数据
editor.commit();
SQLite数据库存储
android为了方便对数据库进行创建(onCreate)和升级(onUpdate),专门提供了一个SQLiteOpenHelper帮助类。数据库的操作是增删改查(CRUD).
- 创建数据库和建立表(Create)
- 创建一个自定义的帮助类继承自抽象类SQLiteOpenHelper,必须重写onCreate()和onUpdate()两个抽象方法。定义帮助类的构造函数,SQLiteOpenHelper(Context context, String DataBaseName, CursorFactory factory, int version);
- 实例化自定义的帮助类,调用getReadableDatabase()或getWritableDatabase()打开或创建一个数据库,返回可读写的数据库对象
- 要在数据库中建立一个表,调用db.execSQL();参数传入建表SQL语句。
建立表
create table [表名]
(
–[字段] [数据类型] [列的特征],
id int identity(1,1) not null,–identity(1,1) 是自动增长(起始值,递增值) ,not null 是不许为空(默认允许为空)
name varchar(20) not null,
)
protected static final String CREATE_BOOK="create table Book(" +
"id integer primary key autoincrement," +
"author text," +
"price real," +
"pages integer," +
"name text," +
"category_id integer)";
- 升级数据库
- 实例化自定义帮助类时,传入不同的版本号id,会调用其中的onUpdata()函数。
- 在onUpdata()函数中进行相关的更新数据库操作。
- 添加数据(Insert)
- 创建一个ContentValue对象,给调用这个对象的put()方法填入(key-value)数据。
- 调用db.insert(String table, String nullColumnHack, ContentValues values),第二个参数一般传入null。
- 更新数据(Update)
- 创建一个ContentValue对象,给调用这个对象的put()方法填入要更新的(key-value)数据。
- 调用public int update(String table, ContentValues values, String whereClause, String[] whereArgs)方法,第三,四个参数是SQL语句的where部分,需要用占位符?来指定具体更新更新哪一行。
`db.update(“Book”, values, “id>?”, new String[]{“1”});
- 删除数据(Delete)
- 调用public int delete(String table, String whereClause, String[] whereArgs)方法。
- 查找数据(Query)
- 调用db.public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having,String orderBy),最简单的用法是除了传入表名外,其他全部传null。此方法返回一个cursor对象
- 遍历Cursor对象,cursor.moveToFirst(),将数据的指针移动到第一行的位置,然后利用循环,调用cursor.get~(cursor,getColumnIndex(“”))方法获得数据,最后调用cursor.moveToNext()。
SQLiteDatabase db=myDatabaseHelper.getWritableDatabase();
Cursor cursor=db.query("Book",null,null,null,null,null,null);
if (cursor.moveToFirst()) {
while(cursor.moveToNext()){
String name=cursor.getString(cursor.getColumnIndex("name"));
String author=cursor.getString(cursor.getColumnIndex("author"));
int pages=cursor.getInt(cursor.getColumnIndex("pages"));
double price=cursor.getDouble(cursor.getColumnIndex("price"));
Log.d("MainActivity","book name is"+name);
Log.d("MainActivity","book author is"+author);
Log.d("MainActivity","book pages is"+pages);
Log.d("MainActivity","book price is"+price);
}
}
cursor.close();
- 使用SQL操作数据库
- 添加数据,SQL语句:insert into table1(field1,field2) values(value1,value2),
db.execSQL(“insert into Book (name,author,pages)values(?,?,?)”,new String[]{“TellH”,”tlh”,”123”}); - 更新数据,SQL语句:update table1 set field1=value1 where 范围,
db.execSQL(“updata Book set price=? where name=?”,new String[]{“123”,”TellH”}); - 删除数据,SQL语句:delete from table1 where 范围,
db.execSQL(“delete from Book where pages>?”,new String[] {“123”}); - 查询数据,SQL语句,select * from table1 where field1 like ’%value1%’ ;
db.rawQuery(“select * from Book”,null);
- 添加数据,SQL语句:insert into table1(field1,field2) values(value1,value2),
- 使用事务 ,保证一系列的操作要么全部完成,要么一个都不会完成。
SQLiteDatabase db=myDatabaseHelper.getWritableDatabase();
db.beginTransaction();
try {
db.delete("Book",null,null);
if (true) {
throw new NullPointerException();
}
ContentValues values=new ContentValues();
values.put("name","Game");
values.put("author","TT");
values.put("pages",123);
values.put("price",222);
db.insert("Book", null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
}finally {
db.endTransaction();//如果事务没有执行成功,删除操作是不能生效的。
}
参考的资料和文献:
DataOutputStream、FileOutputStream和ByteArrayOutputStream:http://m.blog.csdn.net/blog/linchengzhi/7620634
java中的IO操作:http://www.zaojiahua.com/1453.html
经典SQL语句大全: http://www.cnblogs.com/yubinfeng/archive/2010/11/02/1867386.html