-
持久化技術分為3種,文件,sharedPreferences存儲,數據庫來存儲;
目錄
文件存儲:
SQLite創建數據庫
更新
添加
刪除
查找:
文件存儲:
文件存儲是 Android 中最基礎的持久化方式,適合保存結構簡單、體積小的文本或二進制數據,如日志、配置、緩存等,使用方便且無需數據庫支持;但它不適合處理結構復雜或需要頻繁查詢的數據,缺乏并發處理能力與查詢效率,且操作繁瑣,維護成本高。適用于對數據結構要求不高的場景;
把數據存入到文件中:
通過openFileOutput()參數有兩個,第一個是省略包名的文件名,不寫路徑,第二個參數是存儲的方式,是追加還是新存,MODE_PRIVATE代表追加,MODE_END代表新存,返回的是一個fileoutput對象;
FileOutputStream out = null;BufferedWriter writer = null;try {out = openFileOutput(FILE_NAME, MODE_PRIVATE);writer = new BufferedWriter(new OutputStreamWriter(out));writer.write(inputText);} catch (IOException e) {e.printStackTrace();} finally {try {if (writer != null) writer.close();} catch (IOException e) {e.printStackTrace();}}
在活動銷毀之前調用這個方法
把數據從文件取出:
openfileinput()只有一個參數就是文件名;思路構建inputstreamreader對象,構建buffedreader對象,最后利用readline讀入;
代碼如下:
try {in = openFileInput(FILE_NAME);reader = new BufferedReader(new InputStreamReader(in));String line;while ((line = reader.readLine()) != null) {content.append(line).append("\n");}} catch (IOException e) {e.printStackTrace();} finally {try {if (reader != null) reader.close();} catch (IOException e) {e.printStackTrace();}}
根據例子新學到的知識:
editview的方法: settext方法可以把數據放到編輯框里;
setSelection(長度),定光標
TextUtils.isempty(字符串)判空
利用ShatedPreferenecs存儲
?以上的實例總結是我個人的學習總結,各位可用于知識點的復習,如果不需要可跳過;
利用SharedPreferences中讀取數據
SharedPreferences
是 Android 中專門用于 保存少量鍵值對數據的持久化方式,適合保存用戶的配置信息、登錄狀態、設置項等;它本質上使用 XML 文件 存儲數據,操作簡單、高效、安全;
存入
有三種獲得sharedpreferences的方法:
利用Context類中的方法:getSharedPreferences()方法;參數是文件名+類型只有(MODE——PRIVATE方法)
利用Activity類中的方法:getPrefereences()方法 參數只有類型,會把類名作為文件名
利用PreferenceManager類中的getDefaultSgatedPreferences()方法 參數只有context;
獲取到sharedpreferences對象之后的做法
-
New一個editor對象
-
put數據
-
apply()開啟
代碼示例如下:
SharedPreferences.Editor edit = getSharedPreferences("name",MODE_PRIVATE).edit();
edit.putInt("int",8);
edit.putBoolean("boolean",true);
edit.apply();
讀取
-
getshatedpreferences方法得到對象
-
通過get數據獲取,參數有二,第一是鍵,第二是找不到以什么返回;
SharedPreferences preferences = getSharedPreferences("name",MODE_PRIVATE);
int q = preferences.getInt("int",0);
Log.d("ints","int is");
案例
學到這里,有一個關于密碼記憶的案例:在登錄界面,有一個選項,會將你這次登錄成功的密碼進行保存;那么我們一起來看看這個案例吧;
?在點擊之后的邏輯是如果你點了,進行保存,如果沒點,就調用clear方法;
public void onClick(View view) {String s1 = a.getText().toString();String s2 = b.getText().toString();if(s1.equals("797923")&&s2.equals("2983")){edit = pre.edit();if(f.isChecked()){edit.putString("zh",s2);edit.putString("mima",s1);edit.putBoolean("jy",true);}else{edit.clear();}edit.apply();Intent intent = new Intent(LoginActivity.this,MainActivity.class);startActivity(intent);finish();}
}
如果是初次登錄,記得獲取boolean的值的時候,第二個參數為false,必須要通過這個值我才能知道你當時有無選擇復選框;,然后如果為true,那么就進行獲取值,然后settext,也設置復選框:
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_login);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);return insets;});pre = getSharedPreferences("wj",MODE_PRIVATE);button =(Button) findViewById(R.id.psss);a = (EditText) findViewById(R.id.password);b = (EditText) findViewById(R.id.accout);f= (CheckBox) findViewById(R.id.ck);boolean iff = pre.getBoolean("jy", false);if(iff){String c = pre.getString("zh","q");String d = pre.getString("mima","q");a.setText(d);b.setText(c);f.setChecked(true);}button.setOnClickListener(this);
}
SQLite創建數據庫
SQLite 是 Android 中內置的數據庫系統,適合存儲中等規模、結構化的本地數據,支持標準 SQL 操作。
getWritableDatabase和getReadableDatabase方法有什么不同
getWritableDatabase和getReadableDatabase方法有什么不同: 前者,可度可寫也可以查刪,但是如果磁盤滿了,寫入會崩潰;后者:未滿會返回可寫數據庫,但你不能寫,寫了可能崩潰,滿了返回安全的可度數據庫
一個類SQLiteOpenHelper是一個抽象類,想要創建數據庫需要自定義一個類去繼承,然后重寫方法,創建表,把表的創建放進OnCreat里面,這樣new對象的時候創建好數據庫的時候,也可以創建好表:對象.execSQL(表名)
建表語句
好嘛,這里先介紹一下建表語句:
public static final String CREATE_BOOK = "create table Book (" +"id integer primary key autoincrement,"+"author text,"+"price real," +"pages Integer," +"name text)";
CREATE_BOOK:表的語句名;
create table Book (:第一行這里:Book代表表名;
后面的行:第一個代表列名,第二個代表類型,這里給出類型
text? ?文本? ? ?real? 浮點數? ?Integer? 整數? blob 二進制
接下來看看怎么創建數據庫把:
自定以類
建表,構造,重寫方法;
public class MyDatabaseHelper extends SQLiteOpenHelper {private Context mycontext;public static final String CREATE_BOOK = "create table Book (" +"id integer primary key autoincrement,"+"author text,"+"price real," +"pages Integer," +"name text)";public MyDatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {super(context, name, factory, version);mycontext = context;}@Overridepublic void onCreate(SQLiteDatabase sqLiteDatabase) {sqLiteDatabase.execSQL(CREATE_BOOK);Toast.makeText(mycontext,"create yse",Toast.LENGTH_LONG).show();}@Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}
創建對象,調用getweitabledatabase方法可以創建數據庫;
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_main);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);return insets;});MyDatabaseHelper mdh = new MyDatabaseHelper(this,"book.db",null,1);@SuppressLint({"MissingInflatedId", "LocalSuppress"}) Button a = (Button)findViewById(R.id.DT);a.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {mdh.getWritableDatabase();}});}
}
更新
如果你要更新,比如你要添加表,但是Oncreate只會在創建庫的時候啟動一次,這個時候刪除程序不理智,在upgrade方法中,刪除已經存在的表格(否則會報錯).exec("drop table if exits 表名"),然后調用creat方法,最后在創建數據庫對象時,改版本號;
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {sqLiteDatabase.execSQL("drop table if exists BOOK");onCreate(sqLiteDatabase);
}
添加
得到SQiteDatabase對象之后,有一個添加方法:insert方法
三個參數,第一個表名,第二個Null不添加數據的情況下的一列可以為Null 為null,第三個參數傳入的值
這里是一個對象ContentValues對象,這個對象的方法put(第一個參數是項,第二個參數是數據);
SQLiteDatabase aqd = mdh.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name","zh");
values.put("author","1");
values.put("pages",677);
values.put("price",90.8);
aqd.insert("BOOK",null,values);
刪除
delete()
用于按條件刪除表中數據,相信你立馬就可以理解,這個代碼是刪除大于700頁的行了
SQLiteDatabase aqd = mdh.getWritableDatabase();
aqd.delete("BOOK","pages > ?" ,new String[]{"700"});
查找:
通過query方法得到cursor方法,
通過getstring,
外層為行,內層確定列
我們可以看到有多個參數,很是難記,但我們一般就第一個參數寫表名,后面參數全是null了
最近記得關閉
Cursor cr = mdh.getWritableDatabase().query("BOOK",null,null,null,null,null,null);
if(cr.moveToFirst()){do{Log.e("MainActivity","book page is");String names = cr.getString(cr.getColumnIndexOrThrow("name"));String author = cr.getString(cr.getColumnIndexOrThrow("author"));double jg = cr.getDouble(cr.getColumnIndexOrThrow("price"));int page = cr.getInt(cr.getColumnIndexOrThrow("pagesr"));Log.e("MainActivity","book name is"+names);Log.e("MainActivity","book page is"+page);}while(cr.moveToNext());
}
cr.close();
但我們是學習嘛,還是把其他參數也看看吧!
Cursor cursor = db.query("Book", // 表名null, // 要查詢的列(null 表示全部)"author = ?", // 查詢條件new String[]{"曹雪芹"}, // 條件參數null, null, null // 分組、排序等
);
好啦,本次分享到此結束!