文件存儲:
- 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