current position:Home>Android database master script (9), hurry to use litepal version 2.0
Android database master script (9), hurry to use litepal version 2.0
2022-01-27 05:02:17 【Guo Lin】
Preface
I'm glad to tell you some good news today ,LitePal There's a new version .
Forget it , The last version 1.6.1 It was launched half a year ago , And the whole open source project started from 2014 Since its launch in , I've been maintaining it for four years . Over the past four years , I'm constantly perfecting LitePal Code for , Fix all kinds of suggestions bug, And add a variety of new features that are easy to use . Today, , After half a year ,LitePal Finally ushered in a big version update , Officially released 2.0.0 edition !
from 1.6.1 Directly across to 2.0.0, It shows that the upgrade is still very big . stay 2.0.0 In the version , I refactored a lot of internal code , bring LitePal The overall architecture is more reasonable and clear ,API The interface is more scientific , And it rewrites the synchronization mechanism of the database , Solve a lot of concurrent database operation problems . most important of all ,LitePal 2.0.0 Version now fully supports Kotlin 了 ! In the future, whether you use Java still Kotlin Development Android Program , Fine 100% Use compatible LitePal, Is it a little excited ? So let's learn how to use the new version of LitePal Well .
The way to upgrade
The way to upgrade is simple , If you're using Android Studio, Only need build.gradle Modify the configuration in :
dependencies {
implementation 'org.litepal.android:core:2.0.0'
}
Copy code
If you still use Eclipse, Then you can click here Download the latest version jar package .
What we need to pay attention to is ,2.0.0 Almost all of the API All the interfaces have changed . But please don't panic ,2.0.0 The version is fully backward compatible , in other words , You don't have to worry about a lot of errors after the upgrade , Before all the code can still run normally , It's just the old one API Will be marked as abandoned , Remind everyone to use the new one as soon as possible API nothing more , As shown in the figure below :
Of course , You don't have to hear everything API I feel panic when everything changes , In fact, all changes are regular .
So we all know ,LitePal Its usage is very simple , So upgrade new API The process is also very simple , Let's take a step-by-step look at .
First, the inheritance of entity classes needs to be modified , This is how we used to write :
You can see , Now? DataSupport Class has been marked as obsolete , Although it can work normally for the time being , But it's not recommended to use it any more , from LitePal 2.0.0 It is suggested to use LitePalSupport class , We can change the code as follows :
Change the inheritance structure of the entity class to LitePalSupport after , One of the hidden benefits is that all the examples CRUD Methods are automatically upgraded to 2.0.0 Version of the , Such as save() Method ,update() Method ,delete() Methods, etc. . therefore , We used to store a piece of data how to write , Now how to write , such as :
Song song = new Song();
song.setName("hello");
song.setDuration("180");
song.save();
Copy code
In this way, a piece of data can be stored in the database , There is no change in the way it was written before , But it uses LitePal 2.0.0 The latest interface in , Because of this save() The method comes from LitePalSupport Class .
The next step to upgrade is static CRUD Method . It turns out that all the static CRUD Methods are encapsulated in DataSupport Class , For example, the data in the query database that we demonstrated just now can be written in this way :
And now , All the static CRUD Methods have been moved to LitePal Class , So we just need to put DataSupport It is amended as follows LitePal that will do , Other uses are completely unchanged , As shown below :
you 're right , The upgrade process is so simple . To sum up, there are only two main points , If you're using... In an inheritance structure DataSupport, So change it to LitePalSupport, If you're calling DataSupport Static methods in , So change it to LitePal.
But finally, there's one more thing to note , If your project code has enabled obfuscation , Then the confused configuration needs to be modified accordingly , The original confusion configuration is as follows :
-keep class org.litepal.** {
*;
}
-keep class * extends org.litepal.crud.DataSupport {
*;
}
Copy code
And because the DataSupport Classes have been abandoned , So here we also need to confuse the file with DataSupport Change to LitePalSupport Talent , As shown below :
-keep class org.litepal.** {
*;
}
-keep class * extends org.litepal.crud.LitePalSupport{
*;
}
Copy code
After finishing all the above operations , So congratulations , Your code has been completely upgraded to LitePal 2.0.0 Version of the .
Kotlin Since last year Google IO The conference became Android After the first level language , After more than a year of development , Now it has officially become Google Kiss my son . Future use Kotlin To write Android There will be more and more people in the program , therefore LitePal Follow up in time , Full support Kotlin Language .
Now I'll give you a brief demonstration of how to use Kotlin The code uses LitePal Well .
LitePal Use Method
First define an entity class , Here we use Book Class, for example . such as Book There are id、name、page These three fields , And inherit from LitePalSupport class , As shown below :
class Book(val name: String, val page: Int) : LitePalSupport() {
val id: Long = 0
}
Copy code
You can see ,Kotlin It's really simple to define entity classes in . It should be noted that , If you need to define in your entity class id This field , Don't put it in the constructor , because id The value of is determined by LitePal Automatically assigned , It should not be specified by the user . So we are here Book Class declares a read-only type id.
Then it needs to be in litepal.xml Declare this entity class in , This is a routine operation :
<list>
<mapping class="org.litepal.litepalsample.model.Book" />
</list>
Copy code
Okay ! And then we can do CRUD Operation , Well, since it's the first time Kotlin To operate LitePal, Here I will demonstrate each operation separately . The first is storage operations , The code is as follows :
val book = Book(" First line of code ", 552)
val result = book.save()
Log.d(TAG, "save result is $result , book id is ${book.id}")
Copy code
You can see , Here we first create a Book Example , And pass in the title and the number of pages , And then call save() Method can store this data in the database . At the end of the storage, a print log is used to print out the execution results , As shown below :
D/MainActivity: save result is true , book id is 1
Copy code
You can see , This shows that the storage was successful , also book Of id The value has become 1, explain LitePal After the storage is successful id Assigned a value to .
Next, let's take a look at the database , As shown in the figure below :
Once again, verify that the storage operation has been successful .
Now let's show you how to modify , The code is as follows :
val cv = ContentValues()
cv.put("name", " Second line of code ")
cv.put("page", 570)
LitePal.update(Book::class.java, cv, 1)
Copy code
Basically Kotlin Everyone will feel familiar with the usage of "on" , Because and Java It's all similar , It's just that the specific grammar may be a little different . Like update() The first parameter the method receives is a Class object , stay Java We'll introduce Book.class, And in the Kotlin In the middle, you need to pass in Book::class.java.
Execute the above code , Then check it in the database , The results are shown in the following figure :
you 're right , We have successfully completed the modification .
Let's take a look at the delete operation , The code is as follows :
LitePal.delete(Book::class.java, 1)
Copy code
Here we indicate to delete id by 1 This record of . Except, of course, according to id Delete other than , You can also delete according to any other conditions , For example, we want to make the number of pages larger than 500 All the books in the book were deleted , Then you can write :
LitePal.deleteAll(Book::class.java, "page > ?", "500")
Copy code
good , Now execute any of the above lines of code , Then go to the database and observe , As shown in the figure below :
No problem , You can see that the database is empty , It shows that our delete operation has taken effect .
Last , Let's show you the operation of query . Because there is no data in the database now , So let's first add two pieces of data to the library , Then perform the query operation , The code is as follows :
Book(" First line of code ", 552).save()
Book(" Second line of code ", 570).save()
LitePal.findAll(Book::class.java).forEach {
Log.d(TAG, "book name is ${it.name} , book page is ${it.page}")
}
Copy code
Here we call findAll() Method , take Book All the data in the table has been queried . The result of the query is a List aggregate , So we used Kotlin Medium forEach The loop prints out every record it finds . The results are shown below :
D/MainActivity: book name is First line of code , book page is 552
D/MainActivity: book name is Second line of code , book page is 570
Copy code
Of course , In addition to the call findAll() Out of the way , We can also use LitePal To customize the query conditions arbitrarily :
LitePal.where("name like ?", " The first _ Line code ")
.order("page desc")
.limit(5)
.find(Book::class.java)
Copy code
So we'll be in Kotlin Use in LitePal Conduct CRUD All the operations are demonstrated , Is it feeling and Java It's as simple and convenient as in ? Of course , In addition to these new features , I also fixed some known bug, Improve the stability of the overall framework , If that's what you need , Then upgrade quickly .
copyright notice
author[Guo Lin],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270502153108.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command