一.Sqlite在安卓中應用廣泛,主要存儲一些數據,我們可以對他進行增刪查改等操作。
- 什么是Sqlite數據庫?
這個應用程序允許你瀏覽Android上SQLite數據庫。你可以選擇從以下三種方法打開數據庫。1.打開數據庫文件直接。2.發送一個意圖和內容提供商的uri。3.發送一個意圖和數據庫文件的完整路徑。 - 應用設計
SQLite是一個嵌入式庫并且實現了零配置、無服務端和事務功能的SQL數據庫引擎。它在廣泛領域內被使用,而且單線程讀寫性能與MySQL比肩,并且保證ACID性。
SQLite的存儲后端是采用Btree實現,多個連接可以并發操作,但是同一時間只允許一個寫著存在。
SQLite在硬盤上一個數據庫一個文件,每個數據庫文件頭部保存有這個數據庫的元信息,包括版本,大小,Btree根節點位置等等。 - 特色
輕量級;獨立;隔離;跨平臺;多語言接口;安全性。 - 如何創造數據庫呢
public class DatabaseHelp extends SQLiteOpenHelper{
public DatabaseHelp(Context context) {
super(context, "test.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table user(username varchar(11) not null,password varchar(20) not null);"); //使用數據庫的語言創造了一個user的表,里面有username和password兩個字段
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { //用于升級數據庫
}
}
SQLiteOpenHelp是系統幫助打開的方法;
接下來就是add 數據啦,
新建一個類-DatabaseActivity
添加數據:
DatabaseHelp databaseHelp=new DatabaseHelp(this);
mSQLiteDatabase=databaseHelp.getWritableDatabase();
//add data IO操作,建議后臺
ContentValues contentValues=new ContentValues();
contentValues.put("username","1234567");//用contentValue.put加入數據
contentValues.put("password","qq1234567"); //
mSQLiteDatabase.insert("user",null,contentValues);
然后是查詢數據:
Cursor cursor = mSQLiteDatabase.query("user", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
int count = cursor.getCount();
for (int i = 0; i < count; i++) {
String username = cursor.getString(cursor.getColumnIndexOrThrow("username")); //取得表中username 的數據
String password = cursor.getString(cursor.getColumnIndexOrThrow("password")); // 取得password的數據
Toast.makeText(MainActivity.this,"帳號是"+username+"密碼是"+password,Toast.LENGTH_LONG).show(); //使用Toast打印數據
}
}
刪除數據:
// delete:
String whereClauseString = "username=?";
String[] whereArgsString = {" "};
mSqLiteDatabase.delete("user", whereClauseString, whereArgsString);
增添數據update:
// update
ContentValues contentValues = new ContentValues();
contentValues.put("password", "10000000000000");
String whereClauseString = "username=?";
String[] whereArgsString = {"自己的數據"};
mSqLiteDatabase.update("uesr",contentValues, whereClauseString, whereArgsString);
二. Content Provider
- 應用程序間數據的共享
- 為存儲和獲取數據提供了統一的接口
- android為一些數據提供了默認的Content Provider
- 四大組件之一
來自geogle的定義: - 內容提供者將一些特定的應用程序數據提供給其他應用程序使用
- 數據可以用于存儲件系統,SQLite數據庫或其他方式
- 內容提供者繼承于Content Provider基類,為其他應用程序取用和存儲管理他的方法作為替代
- 應用程序并不是直接調用這些方法,而是使用ContentResolver對象,調用他的方法作為替代
- ContentResolver可以與任意內容提供者進行會話,與其合作來對所有相關交互通訊進行管理