三种简单的数据持久化技术
一、文件存储
保存文本到文件
private void save(String inputText) {
FileOutputStream outputStream;
BufferedWriter bufferedWriter = null;
try {
outputStream = openFileOutput("data",Context.MODE_PRIVATE);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(inputText);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedWriter != null){
try {
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
从文件中读取文本
private String load(){
FileInputStream inputStream;
BufferedReader bufferedReader = null;
StringBuilder content = new StringBuilder();
try {
inputStream = openFileInput("data");
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (bufferedReader != null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
二、SharedPreferences存储
SharedPreferences是使用键值对的方式来存储数据,支持不同数据类型存储
3种得到SharedPreferences对象的方法
- Context类中的getSharedPreferences()方法
- Activity类中的getSharedPreferences()方法
- PreFerenceManager类中的getDefaultSharedPreference()方法
保存数据到SharedPreferences
SharedPreferences.Editor editor = getSharedPreferences("data",
MODE_PRIVATE).edit();
editor.putBoolean("love",true);
editor.putFloat("money",1000000.0F);
editor.putString("name","Mickey");
editor.apply();
读取SharedPreferences中的数据
SharedPreferences sharedPreferences = getSharedPreferences("data",
MODE_PRIVATE);
//如果未找到项目的值,就会使用方法中传入的默认值来代替
boolean love = sharedPreferences.getBoolean("love",true);
float money = sharedPreferences.getFloat("money",0F);
String name = sharedPreferences.getString("name","");
三、数据库存储
SQLite数据库存储
1、创建数据库
利用SQLiteOpenHelper帮助类创建数据库。
新建一个类去继承SQLiteOpenHelper抽象类,
重写onCreate()、onUpgrade()两个方法以实现创建和升级数据库的逻辑。
可以使用Android SDK 的ADB命令查看是否已在设备中成功创建了数据库
MyDataBasesHelper帮助类
package com.yxliu.demo.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String CREATE_BOOK = "create table Book(" +
"id integer primary key autoincrement," +
"author text," +
"price real," +
"pages integer," +
"name text)";
private static final String CREATE_CATEGORY = "create table Category(" +
"id integer primary key autoincrement," +
"category_name text," +
"category_code integer)";
private Context mContext;
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext,"Create succeeded",Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
}
}
实例化dbHelper以创建BookStore.db
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 4);
findViewById(R.id.btn_create_database).setOnClickListener(v -> dbHelper.getWritableDatabase());
2、升级数据库
数据库升级时如发现原来的表已存在就会直接报错,所以升级之前需要把原来的表删除,然后再创建
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
}
3.向表中添加数据
findViewById(R.id.btn_add_data).setOnClickListener(v -> {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
// 第一条数据
values.put("name", "First Love2");
values.put("author", "屠格涅夫");
values.put("pages", 600);
values.put("price", 29.9);
db.insert("Book", null, values);
values.clear();
// 第二条数据
values.put("name", "Sense and Sensibility");
values.put("author", "Jane Austen");
values.put("pages", 448);
values.put("price", 52.10);
db.insert("Book", null, values);
Toast.makeText(this, "Add succeeded", Toast.LENGTH_SHORT).show();
});
4、更新数据
findViewById(R.id.btn_update_data).setOnClickListener(v -> {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price", 19.99);
db.update("Book", values, "name = ?", new String[]{"Sense and Sensibility"});
Toast.makeText(SQLiteActivity.this,"update succeeded",Toast.LENGTH_SHORT).show();
});
5、删除数据
findViewById(R.id.btn_delete_data).setOnClickListener(v -> {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("Book", "pages > ?", new String[]{"500"});
Toast.makeText(SQLiteActivity.this,"delete succeeded",Toast.LENGTH_SHORT).show();
});
6、查询数据
findViewById(R.id.btn_query_data).setOnClickListener(v -> {
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("Book",null,null,null,null,null,null);
if (cursor.moveToFirst()){
do {
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("SQLiteActivity---","Book name is " + name);
Log.d("SQLiteActivity---","Book author is " + author);
Log.d("SQLiteActivity---","Book pages is " + pages);
Log.d("SQLiteActivity---","Book price is " + price);
}while (cursor.moveToNext());
}
cursor.close();
Toast.makeText(SQLiteActivity.this,"Query succeeded",Toast.LENGTH_SHORT).show();
});
7、使用SQL操作数据库
- 添加数据
db.execSQL("insert into Book (name, author, pages,price) values (?, ?, ?, ?)", new String[]{"Sense and Sensibility", "Jane Austen", "448", "52.10"});
- 更新数据
db.execSQL("update Book set price = ? where name = ?",new String[]{"19.99","Sense and Sensibility"});
- 删除数据
db.execSQL("delete from Book where pages > ?",new String[]{"550"});
- 查询数据
db.rawQuery("select * from Book",null);
LitePal数据库存储
1、集成LitePal
在app/build.gradle添加依赖
implementation 'org.litepal.android:core:2.0.0'
2、初始化LitePal
- 在AndroidManifest注册LitePalApplication
android:name="org.litepal.LitePalApplication"
- 如果已有Application,则已存在的Application继承LitePalApplication,或者在已存在Application的onCreate()方法中调用LitePal.initialize(context)方法
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
LitePal.initialize(mContext);
}
3、配置映射模型
- 创建javaBean并继承LitePalSupport类(LitePal 2.0版本)
package com.yxliu.demo.model;
import org.litepal.crud.LitePalSupport;
import java.io.Serializable;
public class Book extends LitePalSupport implements Serializable {
private Integer id;
private String name;
private String author;
private Double price;
private Integer pages;
private String press;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getPages() {
return pages;
}
public void setPages(Integer pages) {
this.pages = pages;
}
public String getPress() {
return press;
}
public void setPress(String press) {
this.press = press;
}
}
- 在assets文件夹中添加LitePal.xml
<?xml version="1.0" encoding="utf-8"?>
<litepal>
<dbname value="BookStore" />
<version value="1" />
<list>
<mapping class="com.yxliu.demo.model.Book"/>
</list>
</litepal>
- 调用LitePal.getDatabase()启动数据库
findViewById(R.id.btn_pal_create_database).setOnClickListener(v -> LitePal.getDatabase());
4、LitePal的更新数据库
修改表:只需要修改对应的javaBean
新增表:新增对应的javaBean然后在LitePal.xml的<list>的标签下配置mapping
最后修改版本号大于之前版本号即可
<?xml version="1.0" encoding="utf-8"?>
<litepal>
<dbname value="BookStore" />
<version value="2" />
<list>
<mapping class="com.yxliu.demo.model.Book"/>
<mapping class="com.yxliu.demo.model.Category"/>
</list>
</litepal>
5、LitePal的CRUD
- 新增
findViewById(R.id.btn_pal_add_data).setOnClickListener(v -> {
Book book = new Book();
book.setName("Sense and Sensibility");
book.setAuthor("Jane Austen");
book.setPages(448);
book.setPrice(52.99);
book.setPress("Unknow");
book.save();
Book book2 = new Book();
book2.setName("First Love");
book2.setAuthor("屠格涅夫");
book2.setPages(448);
book2.setPrice(52.99);
book2.setPress("Unknow");
book2.save();
});
- 修改
findViewById(R.id.btn_pal_update_data).setOnClickListener(v -> {
Book book = new Book();
book.setPress("Anchor");
book.setPrice(9.99);
book.updateAll("name = ? and author = ?", "Sense and Sensibility", "Jane Austen");
});
- 删除
findViewById(R.id.btn_pal_delete_data).setOnClickListener(v -> LitePal.deleteAll(Book.class, "price > ?", "10"));
- 查询
findViewById(R.id.btn_pal_query_data).setOnClickListener(v -> {
// 其他查询语句
// List<Book> bookList = LitePal.select("name","author").find(Book.class);
// List<Book> bookList = LitePal.where("pages > ?","400").find(Book.class);
// List<Book> bookList = LitePal.order("price desc").find(Book.class);
// List<Book> bookList = LitePal.limit(3).find(Book.class);
// offset(1)查询结果的偏移量为一
// List<Book> bookList = LitePal.limit(3).offset(1).find(Book.class);
List<Book> bookList = LitePal.select("name","author","pages")
.where("pages > ?","400")
.order("pages")
.limit(3)
.offset(1)
.find(Book.class);
// List<Book> bookList = LitePal.findAll(Book.class);
for (Book book : bookList) {
Log.d("LitePalActivity---", "Book name is " + book.getName());
Log.d("LitePalActivity---", "Book author is " + book.getAuthor());
Log.d("LitePalActivity---", "Book pages is " + book.getPages());
Log.d("LitePalActivity---", "Book press is " + book.getPress());
Log.d("LitePalActivity---", "Book price is " + book.getPrice());
}
});
持续更新中...
网友评论