LitePal的简单使用
程序员文章站
2022-06-24 10:06:23
上截图:首先引入litepal依赖库和butterknife依赖库,完整build.gradle如下:apply plugin: 'com.android.application'android { compileSdkVersion 30 buildToolsVersion "30.0.2" defaultConfig { applicationId "com.example.litepaldemo" minSdkVersion...
上截图:
首先引入litepal依赖库和butterknife依赖库,完整build.gradle如下:
apply plugin: 'com.android.application'
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.litepaldemo"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'org.litepal.guolindev:core:3.2.2'
implementation 'com.jakewharton:butterknife:10.2.3'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'
}
main文件下新建assets文件夹,assets下新加litepal.xml文件(升级数据库修改version中的值就行):
<?xml version="1.0" encoding="utf-8"?>
<litepal>
<!--
Define the database name of your application.
By default each database name should be end with .db.
If you didn't name your database end with .db,
LitePal would plus the suffix automatically for you.
For example:
<dbname value="demo" />
-->
<dbname value="demo" />
<!--
Define the version of your database. Each time you want
to upgrade your database, the version tag would helps.
Modify the models you defined in the mapping tag, and just
make the version value plus one, the upgrade of database
will be processed automatically without concern.
For example:
<version value="1" />
-->
<version value="1" />
<!--
Define your models in the list with mapping tag, LitePal will
create tables for each mapping class. The supported fields
defined in models will be mapped into columns.
For example:
<list>
<mapping class="com.test.model.Reader" />
<mapping class="com.test.model.Magazine" />
</list>
-->
<list>
</list>
<!--
Define where the .db file should be. "internal" means the .db file
will be stored in the database folder of internal storage which no
one can access. "external" means the .db file will be stored in the
path to the directory on the primary external storage device where
the application can place persistent files it owns which everyone
can access. "internal" will act as default.
For example:
<storage value="external" />
-->
</litepal>
然后新建Song类继承LitePalSupport:
package com.example.litepaldemo;
import org.litepal.crud.LitePalSupport;
public class Song extends LitePalSupport {
private long id;
private String name;
private String singer;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
}
MyApplication继承Application并初始化LitePal:
package com.example.litepaldemo;
import android.app.Application;
import org.litepal.LitePal;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LitePal.initialize(this);
}
}
配置文件中引入MyApplication:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.litepaldemo" >
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
使用:
创建数据库并生成自建的Song表:
LitePal.getDatabase();
新增数据:
Song song = new Song();
song.setName("*飞翔");
song.setSinger("凤凰传奇");
song.save();
删除单条数据(根据id删除):
LitePal.delete(Song.class, Long.parseLong(etId.getText().toString()));
修改单条数据(根据id修改):
private void update(long id) {
Song songUpdate = new Song();
songUpdate.setName(etUpdateName.getText().toString());
songUpdate.setSinger(etUpdateSinger.getText().toString());
songUpdate.update(id);
}
查询所有数据并显示:
private void findAll() {
List<Song> allSongs = LitePal.findAll(Song.class);
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < allSongs.size(); i++) {
stringBuffer.append(allSongs.get(i).getId() + ":" + allSongs.get(i).getName() + "--" + allSongs.get(i).getSinger() + "\n");
}
tvContext.setText(stringBuffer);
}
根据id查询单条数据:
Song song = LitePal.find(Song.class, Long.parseLong(s.toString()));
删除数据库下的所有表内容:
LitePal.deleteDatabase("demo");
主要代码:
package com.example.litepaldemo;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.litepal.LitePal;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.et_name)
EditText etName;
@BindView(R.id.et_singer)
EditText etSinger;
@BindView(R.id.btn_add)
Button btnAdd;
@BindView(R.id.tv_context)
TextView tvContext;
@BindView(R.id.et_id)
EditText etId;
@BindView(R.id.btn_del)
Button btnDel;
@BindView(R.id.et_update_id)
EditText etUpdateId;
@BindView(R.id.et_update_name)
EditText etUpdateName;
@BindView(R.id.et_update_singer)
EditText etUpdateSinger;
@BindView(R.id.btn_update)
Button btnUpdate;
@BindView(R.id.btn_getDatabase)
Button btnGetDatabase;
@BindView(R.id.btn_delDatabase)
Button btnDelDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
findAll();
etUpdateId.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (!TextUtils.isEmpty(s.toString())) {
//查单条
Song song = LitePal.find(Song.class, Long.parseLong(s.toString()));
if (song != null) {
etUpdateName.setText(song.getName());
etUpdateSinger.setText(song.getSinger());
}
}
}
});
}
/**
* 查所有
*/
private void findAll() {
List<Song> allSongs = LitePal.findAll(Song.class);
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < allSongs.size(); i++) {
stringBuffer.append(allSongs.get(i).getId() + ":" + allSongs.get(i).getName() + "--" + allSongs.get(i).getSinger() + "\n");
}
tvContext.setText(stringBuffer);
}
/**
* 改单条
*
* @param id
*/
private void update(long id) {
Song songUpdate = new Song();
songUpdate.setName(etUpdateName.getText().toString());
songUpdate.setSinger(etUpdateSinger.getText().toString());
songUpdate.update(id);
}
@OnClick({R.id.btn_add, R.id.btn_del, R.id.btn_update, R.id.btn_getDatabase, R.id.btn_delDatabase})
public void onViewClicked(View view) {
switch (view.getId()) {
//新增
case R.id.btn_add:
if (TextUtils.isEmpty(etName.getText().toString()) || TextUtils.isEmpty(etSinger.getText().toString())) {
Toast.makeText(this, "歌手或歌名不能为空", Toast.LENGTH_SHORT).show();
} else {
Song song = new Song();
song.setName(etName.getText().toString());
song.setSinger(etSinger.getText().toString());
song.save();
findAll();
}
break;
//删除
case R.id.btn_del:
if (TextUtils.isEmpty(etId.getText().toString())) {
Toast.makeText(this, "请输入要删除的id", Toast.LENGTH_SHORT).show();
} else {
//删除单条
LitePal.delete(Song.class, Long.parseLong(etId.getText().toString()));
findAll();
}
break;
//修改单条数据
case R.id.btn_update:
if (TextUtils.isEmpty(etUpdateId.getText().toString())) {
Toast.makeText(this, "id不能为空", Toast.LENGTH_SHORT).show();
} else {
//修改单条
update(Long.parseLong(etUpdateId.getText().toString()));
findAll();
}
break;
//创建数据库
case R.id.btn_getDatabase:
LitePal.getDatabase();
Song song = new Song();
song.setName("*飞翔");
song.setSinger("凤凰传奇");
song.save();
findAll();
break;
//删除数据库
case R.id.btn_delDatabase:
LitePal.deleteDatabase("demo");
findAll();
break;
}
}
}
Demo:https://github.com/cuiwenju2017/LitePalDemo
更多用法见郭神官方Demo:https://github.com/guolindev/LitePal
本文地址:https://blog.csdn.net/juer2017/article/details/110229035
推荐阅读
-
Android自定义View 使用PathMeasure简单模仿系统ProgressBar(四)
-
艺术升app如何进行报考?使用艺术升app进行报考的方法
-
React 使用Hooks简化受控组件的状态绑定
-
Mysql5.7中使用group concat函数数据被截断的问题完美解决方法
-
万兴神剪手中如何调整删除视频片段?使用万兴神剪手调整删除视频片段的方法
-
肉丸子的家常做法有哪些,教你最简单的方法!
-
使用python制作一个为hex文件增加版本号的脚本实例
-
学习node.js 断言的使用详解
-
万兴神剪手转场特效如何使用?使用万兴神剪手为视频添加转场特效的方法
-
CSS3 mask 遮罩的具体使用方法