Android-三种持久化方式详解
-
持久化技术分为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 // 分组、排序等
);
好啦,本次分享到此结束!