最近利用下班时间,找了看什么书比较适合初学android的朋友,很多人推荐了这本书,于是就买了一本,感觉看书,思考,动手,再思考和总结这样过程还是很有必要的,于是就打算把自己学习的东西简单的总结一下;方便自己以后查找,也有利于学习的巩固。在这里首先要感谢一下书籍的作者——郭霖前辈。
关于数据持久化我在前面三篇已经介绍三种实现方式(操作文件,SP,SQLite数据库实现);今天就来介绍一下LitePal开源库的基本使用,其实在书的前面关于网络那一部分就介绍了一个开源库---OkHttp的使用,只是那一部分我的Demo写了,现在还没有放在博客上,今天刚好也介绍一下开源库的整个使用流程。
1,环境与配置准备
第一步:开源库Jar包的引入
(1)第一种:在app/build.gradle文件的dependencies下添加:
compile 'org.litepal.android:core:LitePal版本号';其中版本号到开源项目主页查询(比如1.4.1)
(2)第二种:直接下载开源项目,解压找到对应jar包,添加在工程libs目录下,右键选择Add as library也行
第二步:在app/src/main目录下,创建一个assets目录,在里面添加litepal.xml文件,主要用于数据库配置,具体内容包括数据库名称,版本以及OR映射(对象/关系)
第三步:在主配置文件中的application的属性中添加一条:
android:name="org,litepal.LitePalApplication"
2,示例代码
下面的示例代码较多,并且在并没有完善,尤其在数据更新没有做二级页面,所以有兴趣的朋友可以继续完善。
MainActivity.java代码:
package com.hfut.litepaldemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import org.litepal.LitePal;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createDB(View view){
LitePal.getDatabase();
Log.i(TAG, "createDB: 执行了创建数据库操作");
}
public void updateDB(View view){
LitePal.getDatabase();
Log.i(TAG, "updateDB: 执行了更新数据库操作");
}
public void operateDB(View view){
Intent intent=new Intent(this,OperationActivity.class);
startActivity(intent);
}
}
Student.java代码:
package com.hfut.litepaldemo;
import org.litepal.crud.DataSupport;
/**
* author:why
* created on: 2018/3/18 14:09
* description:
*/
public class Student extends DataSupport{
private String name;
private int age;
private String sex;
private int stuID;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getStuID() {
return stuID;
}
public void setStuID(int stuID) {
this.stuID = stuID;
}
// @Override
// public String toString() {
// return "stuID="+stuID+";name="+name+";age="+age+";sex="+sex;
// }
}
OperationActivity.java代码:
package com.hfut.litepaldemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import org.litepal.crud.DataSupport;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
public class OperationActivity extends AppCompatActivity {
private static final String TAG = "OperationActivity";
private TextView queryResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_operation);
queryResult=findViewById(R.id.queryResult);
}
public void insertData(View view) {
Intent intent=new Intent(this,AddDataActivity.class);
startActivity(intent);
//Log.i(TAG, "insertData: 执行了添加数据操作");
}
public void deleteData(View view) {
Intent intent=new Intent(this,DeleteDateActivity.class);
startActivity(intent);
}
//把所有姓名为xiaoming的student的性别改为男性
public void updateData(View view) {
Student why = new Student();
why.setSex("male");
why.updateAll("name=?", "xiaoming");
Log.i(TAG, "updateData: 执行了更新数据操作");
}
public void queryData(View view) {
Log.i(TAG, "queryData: 执行了查询数据操作");
BufferedWriter bufferedWriter = null;
OutputStream outputStream = null;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("student表中的数据:\n");
List students = DataSupport.findAll(Student.class);
for (Student student : students) {
stringBuilder.append("stuID=" + student.getStuID() + ";name=" + student.getName() + ";age=" + student.getAge() + ";sex=" + student.getSex() + "\n");
}
String tempString = stringBuilder.toString();
queryResult.setText(tempString);
try {
outputStream = openFileOutput("students.txt", MODE_PRIVATE);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
Log.i(TAG, "queryData: "+tempString);
bufferedWriter.write(tempString);
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
AddDataActivity.java代码:
package com.hfut.litepaldemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AddDataActivity extends AppCompatActivity {
private static final String TAG = "AddDataActivity";
private EditText stuID;
private EditText name;
private EditText age;
private EditText sex;
private TextView addInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_data);
initUI();
}
private void initUI() {
stuID = findViewById(R.id.add_stuID);
age = findViewById(R.id.add_age);
name = findViewById(R.id.add_name);
sex = findViewById(R.id.add_sex);
addInfo = findViewById(R.id.addDataInfo);
}
public void addStudent(View view) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("stuID:" + stuID.getText().toString()+" ").append("name:" + name.getText().toString()+" ")
.append("age:" + age.getText().toString()+" ").append("sex:" + sex.getText().toString()+" ").append("添加时间:"+new Date().toString());
Student student = new Student();
student.setStuID(Integer.parseInt(stuID.getText().toString()));
student.setSex(sex.getText().toString());
student.setAge(Integer.parseInt(age.getText().toString()));
student.setName(name.getText().toString());
student.save();
Log.i(TAG, "addStudent: 执行了添加数据的操作");
stuID.setText("");
name.setText("");
age.setText("");
sex.setText("");
addInfo.append("\n成功添加一条数据:\n");
addInfo.append(stringBuilder.toString());
}
public void backup(View view) {
addInfo.setText("");
finish();
}
}
DeleteDataActivity.java代码:
package com.hfut.litepaldemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.litepal.crud.DataSupport;
import java.util.Date;
public class DeleteDateActivity extends AppCompatActivity {
private EditText stuID;
private EditText name;
private EditText age;
private EditText sex;
private TextView deleteDataInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_date);
initUI();
}
private void initUI() {
stuID = findViewById(R.id.delete_stuID);
name = findViewById(R.id.delete_name);
age = findViewById(R.id.delete_age);
sex = findViewById(R.id.delete_sex);
deleteDataInfo=findViewById(R.id.deleteData);
}
public void deleteStudent(View view) {
StringBuilder stringBuilder=new StringBuilder();
Integer studentID = null;
String studentName = null;
String studentSex = null;
Integer studentAge = null;
if (!TextUtils.isEmpty(stuID.getText().toString())) {
studentID = Integer.parseInt(stuID.getText().toString());
}
if (!TextUtils.isEmpty(name.getText().toString())) {
studentName = name.getText().toString();
}
if (!TextUtils.isEmpty(sex.getText().toString())) {
studentSex = sex.getText().toString();
}
if (!TextUtils.isEmpty(age.getText().toString())) {
studentAge = Integer.parseInt(age.getText().toString());
}
if (studentID != null) {
System.out.println("studentID:" + studentID);
DataSupport.deleteAll(Student.class, "stuID=?", stuID.getText().toString());
stringBuilder.append("您刚刚删除了ID为"+studentID+"的学生信息");
} else {
if (!TextUtils.isEmpty(studentName)) {
if (!TextUtils.isEmpty(studentSex)) {
if (!TextUtils.isEmpty(age.getText().toString())) {
DataSupport.deleteAll(Student.class, "name=? and sex=? and age=?", studentName, studentSex, age.getText().toString());
stringBuilder.append("您刚刚删除了姓名为"+studentName+";性别为"+studentSex+";年龄为"+studentAge+"的所有学生信息");
} else {
DataSupport.deleteAll(Student.class, "name=? and sex=?", studentName, studentSex);
stringBuilder.append("您刚刚删除了姓名为"+studentName+";性别为"+studentSex+"的所有学生信息");
}
} else {
if (!TextUtils.isEmpty(age.getText().toString())) {
DataSupport.deleteAll(Student.class, "name=? and age=?", studentName, age.getText().toString());
stringBuilder.append("您刚刚删除了姓名为"+studentName+";年龄为"+studentAge+"的所有学生信息");
} else {
DataSupport.deleteAll(Student.class, "name=?", studentName);
stringBuilder.append("您刚刚删除了姓名为"+studentName+"的所有学生信息");
}
}
} else {
if (!TextUtils.isEmpty(studentSex)) {
if (!TextUtils.isEmpty(age.getText().toString())) {
DataSupport.deleteAll(Student.class, "sex=? and age=?", studentSex, age.getText().toString());
stringBuilder.append("您刚刚删除了性别为"+studentSex+";年龄为"+studentAge+"的所有学生信息");
} else {
DataSupport.deleteAll(Student.class, "sex=?", studentSex);
stringBuilder.append("您刚刚删除了性别为"+studentSex+"的所有学生信息");
}
} else {
if (!TextUtils.isEmpty(age.getText().toString())) {
DataSupport.deleteAll(Student.class, "age=?", age.getText().toString());
stringBuilder.append("您刚刚删除了年龄为"+studentAge+"的所有学生信息");
} else {
Toast.makeText(this, "请输入要删除的数据", Toast.LENGTH_SHORT).show();
//DataSupport.deleteAll(Student.class, "name=?", studentName);
}
}
}
}
stringBuilder.append(";删除时间"+new Date().toString());
deleteDataInfo.append(stringBuilder.toString()+"\n");
stuID.setText("");
name.setText("");
age.setText("");
sex.setText("");
}
public void deleteAllData(View view) {
DataSupport.deleteAll(Student.class);
}
public void backup(View view) {
deleteDataInfo.setText("");
finish();
}
}
activity_main.xml代码:
activity_operation.xml代码:
activity_add_data.xml代码:
activity_delete_data.xml代码:
build.gradle文件代码:
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.hfut.litepaldemo"
minSdkVersion 22
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'org.litepal.android:core:1.4.1'
}
litepal.xml代码:
3,运行结果
第一步:运行程序
第二步:点击“创建数据库”按钮
第三步:点击“操作数据库”按钮
第四步:点击“查询数据”按钮
第五步:点击“添加数据”按钮
第六步:输入添加数据,然后点击“添加”按钮,多添加几条数据
第七步:点击“退出”按钮,在点击“查询数据”按钮
第八步:点击“删除数据”按钮
第九步:编辑要删除数据信息,点击“删除”按钮
第十步:点击“全部删除”按钮,退出,点击“查询数据”按钮
总结:这篇是关于数据持久化中最后一篇了;LitePal很强大,我这是九牛一毛的深度;我的示例代码中,关于数据更新还没有做,有兴趣的朋友可以完善一下,因为我这里面的stuID定义为主键,所以有唯一性,这样我在逻辑判断的时候也考虑了这一点,所以在已知stuID的情况下,删除信息就不需要其他信息了。
注:欢迎扫码关注