Android SharePreferences與數(shù)據(jù)庫SQLite存儲實現(xiàn)方法介紹
Android數(shù)據(jù)存儲幾種方式
- SharePreferences
- 數(shù)據(jù)庫SQLite
- 存儲卡的文件操作
- Application
一、共享參數(shù)
SharePreferences是Android的一個輕量級存儲工具,采用的存儲結(jié)構(gòu)是Key-Value的鍵值對方式。
共享參數(shù)的存儲介質(zhì)是符合XML規(guī)范的配置文件,保存路徑是:/data/data/應用包名/shared_prefs/文件名.xml
使用場景
共享參數(shù)主要適用于如下場合:
- 簡單且孤立的數(shù)據(jù),若是復雜且相互間有關(guān)的數(shù)據(jù),則要保存在數(shù)據(jù)庫中。
- 文本形式的數(shù)據(jù),若是二進制數(shù)據(jù),則要保存在文件中。
- 需要持久化存儲的數(shù)據(jù),在APP退出后再次啟動時,之前保存的數(shù)據(jù)仍然有效。
實際開發(fā),共享參數(shù)經(jīng)常存儲的數(shù)據(jù)有APP的個性化配置信息、用戶使用APP的行為信息、臨時需要保存的片段信息等。
例:輸入姓名保存到共享參數(shù),重新打開應用會自動輸入到輸入框。

XML文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="姓名"
android:textSize="17sp"/>
<EditText
android:id="@+id/et_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="請輸入姓名"
android:inputType="text"
android:textSize="17sp"/>
</LinearLayout>
<Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存到共享參數(shù)"
android:textSize="17sp"/>
</LinearLayout>java文件
public class ShareWriteActivity extends AppCompatActivity implements View.OnClickListener {
private EditText et_name;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_write);
et_name = findViewById(R.id.et_name);
findViewById(R.id.btn_save).setOnClickListener(this);
// 點擊保存共享參數(shù)則保存數(shù)據(jù)
preferences = getSharedPreferences("config", Context.MODE_PRIVATE);
// 打開應用會檢測是否有保存過的數(shù)據(jù)
reload();
}
private void reload() {
String name = preferences.getString("name",null);
if(name != null){
et_name.setText(name);
}
}
@Override
public void onClick(View view) {
String name = et_name.getText().toString();
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name",name);
editor.commit();
}
}二、數(shù)據(jù)庫SQLite
SQLite是一種小巧的嵌入式數(shù)據(jù)庫,使用方便、開發(fā)簡單,由于屬于輕型數(shù)據(jù)庫,不涉及復雜的數(shù)據(jù)控制操作,因此App開發(fā)只用到數(shù)據(jù)定義和數(shù)據(jù)操縱兩類SQL。
1、數(shù)據(jù)定義語言(DDL)
它描述了怎樣變更數(shù)據(jù)實體的框架結(jié)構(gòu),主要包括三種操作:創(chuàng)建表格、刪除表格、修改表結(jié)構(gòu)。
(1)創(chuàng)建表格
語法:CREATE TABLE IF NOT EXISTS 表格名稱();
說明:
- SQL語句不區(qū)分大小寫。
- 支持整型INTEGER,長整型LONG,字符串VARCHAR,浮點數(shù)FLOAT,但不支持布爾類型,如果使用布爾類型,true轉(zhuǎn)換為1,false轉(zhuǎn)換為0。
- 為避免重復建表,應加上IF NOT EXISTS關(guān)鍵詞。
- 建表時需要唯一標識字段,它的字段名為id。
例:
CREATE TABLE IF NOT EXISTS user_info(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR NOT NULL
);(2)刪除表格
語法:DROP TABLE IF EXISTS 表格名稱;
例:
DROP TABLE IF EXISTS user_info;
(3)修改表結(jié)構(gòu)
語法:ALTER TABLE 表格名稱 修改操作;
說明:
SQLite只支持增加字段,不支持修改字段,也不支持刪除字段,對于字段增加操作,需要在alter之后補充add命令。
例:
ALTER TABLE user_info ADD COLUMN phone VARCHAR;
2、數(shù)據(jù)操縱語言(DML)
描述了怎么樣處理數(shù)據(jù)實體的內(nèi)部記錄,表格記錄的操作類型包括添加、刪除、修改、查詢四類。
(1)添加記錄
語法:INSERT INTO 表格名稱( 以逗號分隔的字段名列表 ) VALUES (以逗號分隔的字段值列表);
例:
INSERT INTO user_info (name,age,height) VALUES ('張',20,64);(2)刪除記錄
語法:DELETE FROM 表格名稱 WHERE 查詢條件;
例:
DELETE FROM user_info WHERE name = '張';
(3)修改記錄
語法:UPDATE 表格名稱 SET 字段名=字段值 WHERE 查詢條件;
例:
UPDATE user_info SET married=1 WHERE name='張';
(4)查詢記錄
語法:SELECT 以逗號分隔的字段名列表 FROM 表格名稱 WHERE 查詢條件;
例:
SELECT name FROM user_info WHERE name='張';
查詢操作除了比較字段值條件外,還可對查詢結(jié)果排序“ORDER BY 字段名 ASC或DESC”
例:
SELECT * FROM user_info ORDER BY age ASC;
三、數(shù)據(jù)庫管理器SQLiteDatabase
若要在java代碼中操縱SQLite,需專門的工具類,SQLiteDatabase是Android提供的SQLite數(shù)據(jù)庫管理器,可調(diào)用openOrCreateDatabase方法獲取數(shù)據(jù)庫實例。
獲取數(shù)據(jù)庫實例后,可開展各項操作,提供了若干操作數(shù)據(jù)表的API,常用方法:
管理類
用于數(shù)據(jù)庫 層面的操作
- openDatabase:打開指定路徑的數(shù)據(jù)庫。
- isOpen:判斷數(shù)據(jù)庫是否已打開。
- close:關(guān)閉數(shù)據(jù)庫。
- getVersion:獲取數(shù)據(jù)庫的版本號。
- setVersion:設(shè)置數(shù)據(jù)庫的版本號。
事務(wù)類
- 用于事務(wù)層面的操作 beginTransaction:開始事務(wù)。
- setTransactionSuccessful:設(shè)置事務(wù)的成功標志。
- endTransaction:結(jié)束事務(wù)。
數(shù)據(jù)處理類
用于數(shù)據(jù)表層面的操作
- execSQL:執(zhí)行拼接好的SQL控制語句。
- delete:刪除符合條件的記錄。
- update:更新符合條件的記錄。
- insert:插入一條記錄。
- query:執(zhí)行查詢操作,返回結(jié)果集的游標。
- rawQuery:執(zhí)行拼接好的SQL查詢語句,返回結(jié)果集的游標。
例:創(chuàng)建、刪除數(shù)據(jù)庫



XML文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_database_create"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="創(chuàng)建數(shù)據(jù)庫"
android:textSize="17sp"/>
<Button
android:id="@+id/btn_database_delete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="刪除數(shù)據(jù)庫"
android:textSize="17sp"/>
</LinearLayout>
<TextView
android:id="@+id/tv_database"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="17sp"/>
</LinearLayout>java代碼
public class DatabaseActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tv_database;
private String mDatabaseName;
private String desc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
tv_database = findViewById(R.id.tv_database);
findViewById(R.id.btn_database_create).setOnClickListener(this);
findViewById(R.id.btn_database_delete).setOnClickListener(this);
// 生成一個測試數(shù)據(jù)庫的完整路徑
mDatabaseName = getFilesDir() + "/test.db";
}
@Override
public void onClick(View view) {
switch (view.getId()){
// 創(chuàng)建或打開數(shù)據(jù)庫,數(shù)據(jù)庫如果不存在則創(chuàng)建
case R.id.btn_database_create:
SQLiteDatabase db = openOrCreateDatabase(mDatabaseName, Context.MODE_PRIVATE,null);
desc = String.format("數(shù)據(jù)庫%s創(chuàng)建%s",db.getPath(),(db != null) ? "成功":"失敗");
tv_database.setText(desc);
break;
case R.id.btn_database_delete:
//刪除數(shù)據(jù)庫
boolean result = deleteDatabase(mDatabaseName);
desc = String.format("數(shù)據(jù)庫%s刪除%s",mDatabaseName,result? "成功":"失敗");
tv_database.setText(desc);
break;
}
}
}四、數(shù)據(jù)庫幫助器SQLiteOpenHelper
SQLiteOpenHelper是Android提供的數(shù)據(jù)庫輔助工具,用于指導開發(fā)者進行SQLite的合理使用。
使用步驟:
- 新建繼承SQLiteOpenHelper的數(shù)據(jù)庫操作類,提示重寫onCreate和onUpgrade兩個方法。
- 封裝保證數(shù)據(jù)庫安全的必要方法。
- 提供對表記錄進行增加、刪除、修改、查詢的操作方法。
例:添加到數(shù)據(jù)庫中


創(chuàng)建database包,包下創(chuàng)建java類
public class UserDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "user.db";
private static final String TABLE_NAME = "user_info";
private static final int DB_VERSION = 1;
private static UserDBHelper mHelper = null;
private SQLiteDatabase mRDB = null;
private SQLiteDatabase mWDB = null;
private UserDBHelper(Context context){
super(context,DB_NAME,null,DB_VERSION);
}
// 利用單例模式獲取數(shù)據(jù)庫幫助器的唯一實例
public static UserDBHelper getInstance(Context context){
if(mHelper == null){
mHelper = new UserDBHelper(context);
}
return mHelper;
}
// 打開數(shù)據(jù)庫的讀連接
public SQLiteDatabase openReadLink(){
if(mRDB == null || !mRDB.isOpen()){
mRDB = mHelper.getReadableDatabase();
}
return mRDB;
}
// 打開寫連接
public SQLiteDatabase openWriteLink(){
if(mWDB == null || !mWDB.isOpen()){
mWDB = mHelper.getWritableDatabase();
}
return mWDB;
}
// 關(guān)閉數(shù)據(jù)庫連接
public void closeLink(){
if(mRDB != null && mRDB.isOpen()){
mRDB.close();
mRDB = null;
}
if(mWDB != null && mWDB.isOpen()){
mWDB.close();
mWDB = null;
}
}
// 創(chuàng)建數(shù)據(jù)庫,執(zhí)行建表語句
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(" +
"id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
"name VARCHAR NOT NULL);";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long insert(User user){
ContentValues values = new ContentValues();
values.put("name",user.name);
return mWDB.insert(TABLE_NAME,null,values);
}
}XML文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="姓名"
android:textSize="17sp"/>
<EditText
android:id="@+id/et_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="請輸入姓名"
android:inputType="text"
android:textSize="17sp"/>
</LinearLayout>
<Button
android:id="@+id/btn_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加"
android:textSize="17sp"/>
</LinearLayout>Userjava類
public class User {
public int id;
public String name;
public User(){
}
public User(String name){
this.name = name;
}
}Activity java類
public class SQLiteHelperActivity extends AppCompatActivity implements View.OnClickListener {
private TextView et_name;
private UserDBHelper mHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlite_helper);
et_name = findViewById(R.id.et_name);
findViewById(R.id.btn_add).setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
// 打開數(shù)據(jù)庫幫助器的實例
mHelper = UserDBHelper.getInstance(this);
// 打開數(shù)據(jù)庫幫助器的讀寫連接
mHelper.openWriteLink();
mHelper.openReadLink();
}
@Override
protected void onStop() {
super.onStop();
mHelper.closeLink();
}
@Override
public void onClick(View view) {
String name = et_name.getText().toString();
User user = null;
switch (view.getId()){
case R.id.btn_add:
// 以下聲明一個用戶信息對象,并填寫它的各字段值
user = new User(name);
if(mHelper.insert(user)>0){
Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show();
}
break;
}
}
}到此這篇關(guān)于Android SharePreferences與數(shù)據(jù)庫SQLite存儲實現(xiàn)方法介紹的文章就介紹到這了,更多相關(guān)Android SharePreferences內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android導入現(xiàn)有的數(shù)據(jù)庫方法示例
這篇文章主要介紹了Android導入現(xiàn)有的數(shù)據(jù)庫方法,文中通過示例代碼介紹的很詳細,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-02-02
淺談Android中關(guān)于靜態(tài)變量(static)的使用問題
本文主要介紹了Android中關(guān)于靜態(tài)變量(static)的使用問題,具有一定的參考作用,下面跟著小編一起來看下吧2017-01-01
Android開發(fā)雙向滑動選擇器范圍SeekBar實現(xiàn)
這篇文章主要為大家介紹了Android開發(fā)雙向滑動范圍選擇器SeekBar實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06

