After studying the previous articles, we have already mastered the functions of Litepal's Table management module, and believe that we have realized the convenience of using Litepal to create tables, upgrade tables, and establish table associations. So from the beginning of this article, we will go into the learning journey of a new module, using Litepal to perform CRUD operations on the table. Friends who have not read the previous article suggested first refer to the Android database master cheats (iv)--using Litepal to establish a table association .
Litepal provides the CRUD operation API is quite rich, an article is certainly not complete, so here we are still a few articles to explain, this article is mainly about the storage aspects of the API.
Litepal's project address is:https://github.com/LitePalFramework/LitePal
Traditional way of storing data
In fact, the most traditional way of storing data is to be stored by concatenation of SQL statements, but this is a bit too "traditional", and today we do not discuss this situation here. In fact, Android specifically provides a convenient way to store data so that we can perform storage operations without writing SQL statements. Here's a look at the insert () method in Sqlitedatabase:
Public long Insert (string table, String nullcolumnhack, contentvalues values)
As you can see, the Insert method receives three parameters, the first parameter is the table name, the second parameter is usually not used, the null is passed directly, and the third parameter is a Contentvalues object that encapsulates the data to be stored. So, for example, if we want to insert a story into the news list, we can write:
Sqlitedatabase db = Dbhelper.getwritabledatabase (); Contentvalues values = new Contentvalues (), Values.put ("title", "This is a news headline"), Values.put ("content", "This is a piece of news"); Values.put ("Publishdate", System.currenttimemillis ()); Long id = Db.insert ("News", null, values);
wherein, call Contentvalues's put () method to add the data to be stored, the put () method receives two parameters, the first parameter is the corresponding column name in the database table, the second parameter is the value to be stored, and finally called the Insert () method, This will be inserted into the news table, and the corresponding ID of the data row will be returned as a return value.
It's easy to use, isn't it? Indeed, the insert () method provided in Sqlitedatabase is a lot simpler than using SQL statements directly. But the insert () method is not so perfect, it still has a lot of inconvenient places, for example, without regard to the case of table Association, we need to manually store the foreign key of the associated table. For example, without the ability to provide bulk storage, when we have a collection of data that needs to be stored, we need to iterate through the collection through loops and then call the Insert () method again and again to insert the data.
Well, the use of traditional storage data is simply introduced here, because there is really nothing more to use, and it is not the protagonist of our day. Next, let's take a look at today's surprises and learn how to use Litepal for database storage operations.
Storing data using Litepal
There are not many storage-related APIs in Litepal, but the usage is quite rich, and the use of Litepal to store data can be simple enough to amaze you than the traditional insert () method, so today we'll take a complete look at all the uses of Litepal storage data.
In the previous several articles, we have already built the news, Comment, Introduction, category these entity class in the project, through these entity class, Litepal can create the corresponding table automatically. Now to observe these entity classes, we find that these classes have no inheritance structure. Yes, because Litepal does not need any inheritance structure for the table management operations when these entity classes are in use, it was not written for the sake of simplicity. However, it is not necessary to perform CRUD operations, Litepal requires all entity classes to inherit from the Datasupport class, so here we will add the inheritance structure to the line. Modify the code for the News class as follows:
public class News extends datasupport{......//automatically generate get, set method}
As you can see, it's just that the news class inherits from Datasupport, and nothing else has changed. Several other comment, Introduction, category categories also use the same method of modification, here is not a demonstration.
After inheriting the Datasupport class, these entity classes have the ability to perform crud operations, such as the need to store a piece of data into the news table, which can be written like this:
News news = new News ("This is a news headline"), News.setcontent ("This is a news content"); News.setpublishdate (new Date ()); news.settitle; News.save ();
What do you think? is not very simple, do not need to sqlitedatabase, do not need to contentvalues, do not need to assemble the data through the column name, even do not need to specify the table name, only need to new a news object, and then the data to be stored through the setter method to pass in, The last call to the Save () method is fine, and the Save () method is naturally inherited from the Datasupport class.
In addition, the Save () method has a return value, and we can determine whether the store is successful based on the return value, such as writing:
if (News.save ()) {Toast.maketext (context, "Storage succeeded", Toast.length_short). Show ();} else {Toast.maketext (context, "Storage failed", Toast.length_short). Show ();}
As you can see, the Save () method returns a Boolean value that indicates whether the store succeeded or failed, but it also indicates that the method does not throw an exception. Some friends want to throw an exception if the store fails, instead of returning a false, you can use the Savethrows () method instead, as shown here:
News news = new News ("This is a news headline"), News.setcontent ("This is a news content"); News.setpublishdate (new Date ()); news.settitle; News.savethrows ();
Using the Savethrows () method to store the data, once the store fails, a Datasupportexception exception is thrown, and we can handle the storage failure by capturing the exception.
Some attentive friends may have noticed that the insert () method used to store the data has a return value, and the ID of the inserted row is returned. But the Save () method in Litepal returns a Boolean value, so how do we get the ID that corresponds to the data after it was successfully stored? In this respect, Litepal used a very ingenious approach, remember that we have an ID field defined in each entity class? When the Save () method is called or the Savethrows () method is stored successfully, Litepal automatically assigns the ID of the data corresponding to the ID field of the entity class. Let's do an experiment, the code looks like this:
News news = new News ("This is a news headline"), News.setcontent ("This is a news content"); News.setpublishdate (new Date ()); news.settitle; LOG.D ("TAG", "News ID is" + news.getid ()); News.save (); LOG.D ("TAG", "News ID is" + news.getid ());
Print the news ID before save, print it again after save, and run it now, and print the results as shown below:
OK, the ID printed before save is 0, indicating that the ID field has not yet been assigned, and the ID printed after save is 1, indicating that the ID has been assigned at this time. So let's go back to the database table and see if this record is stored successfully, as shown in:
As you can see, the news has actually been stored successfully, and the corresponding ID is 1, which is consistent with the results we printed earlier.
However, the Litepal storage function shows that not only these usages, in fact, Litepal in the storage of data silently help us do a lot of things, such as the relationship between multiple entity classes, we do not need to consider how to store data in the time to establish the correlation between data and data, Because Litepal everything has been done for us.
Let's take a look at one example, comment and news is a many-to-one relationship, and a news message can contain multiple comments, so we can write:
comment comment1 = new comment () ; Comment1.setcontent ("Praise! "); Comment1.setpublishdate (New date ()); Comment1.save (); Comment comment2 = new comment (); Comment2.setcontent ("like One"); Comment2.setpublishdate (new date ()); Comment2.save (); News news = new news (); News.getcommentlist (). Add (Comment1); News.getcommentlist (). Add ( COMMENT2); News.settitle ("Second news headline"), News.setcontent ("Second news content"); News.setpublishdate (New date ()); News.setcommentcount (News.getcommentlist (). Size ()); News.save ();
As you can see, this first stores a comment1 data, then stores a comment2 data, and then adds the two comment objects just before storing the news to the Commentlist list of news. This means that the two comment are part of the news object, and then store the news in the database so that the association between them is automatically established. Let's look at the database table and check the news table first, as shown below:
OK, the second piece of news has been successfully stored in the news list, which has an ID of 2. So where do you see the correlation? We learned in the previous article, many to one association, the foreign key is stored in the multi-party, so the correlation relationship we want to go to the comment table to see, as follows:
As you can see, two comments have been successfully stored in the comment table, and the news_id of the two comments are 2, indicating that they belong to the second piece of news. How about, just to set up the relationship between the entity classes before storing the data, and then call the Save () method, then the correlation between the data will be automatically established, is it very simple? The above code is just a one-to-one use of the situation, there is a single-and many-to-many cases, in fact, the usage is almost the same, I believe you have been able to extrapolate.
In addition, Litepal provides a way to store collection data specifically, such as we have a news collection, so how do we store every news in this collection? Traditionally, this can be written like this:
List<news> newslist;...for (News news:newslist) {news.save ();}
Iterate through each of the news objects in the collection through a loop, and then call the Save () method one after the other. This is certainly possible, but the efficiency will be relatively low, because the call to save () method In addition to the execution of storage operations, but also to analyze the relationship of the news class, then each cycle to re-analyze the correlation relationship is obviously more time-consuming. Therefore, Litepal provides a SaveAll () method specifically for storing collection data, as follows:
List<news> newslist; Datasupport.saveall (newslist);
The SaveAll () method receives a collection collection parameter, as long as the collection data to be stored is passed in. This method can accomplish exactly the same function as the previous piece of code, but it is much more efficient and easier to write.
OK, so we've all learned the usage of the storage operations provided in Litepal, so today's article is here, and the next article will begin to explain the usage of the update and delete operations. Interested friends please continue to read the Android database Master cheats (vi)--litepal modification and deletion operations .
Litepal Open Source project address: Https://github.com/LitePalFramework/LitePal
Android database Master cheats (v)--litepal storage operations