Android database Master cheats (v)--litepal storage operations

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/39345833

After studying the previous articles, we have already mastered the functions of Litepal's Table management module very well, I 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 a new module of learning journey where the Litepal is used to perform CRUD operations on the table. Friends who have not read the previous article suggest first to take a look at the Android database master cheats (iv)--using Litepal to establish a table association .

Litepal provides a rich API for CRUD operations, and an article is definitely not an introduction. 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 certainly to be stored by concatenation of SQL statements, but this way is a little too "traditional". We are not going to discuss such a situation here today.

In fact, Android specifically provides a convenient way to store data so that we can run storage operations without writing SQL statements. Take a look at the insert () method in Sqlitedatabase:

Public long Insert (string table, String nullcolumnhack, contentvalues values)
Can see. The Insert method receives three parameters, the first parameter is the table name, the second parameter is usually not used, the direct null is passed, and the third parameter is a Contentvalues object that encapsulates the data to be stored. So let's say we want to insert a story into the news list and 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 piece of news is inserted into news, and the corresponding ID of the data row is returned as a return value.

It's very easy to use, isn't it? Indeed, the insert () method provided in Sqlitedatabase is indeed much 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 considering the table association, we need to manually store the foreign key of the associated table.

Again, for example, there is no capability to provide bulk storage when we have a collection of data that needs to be stored. This collection needs to be traversed through a loop. Then, call the Insert () method again and again to insert the data.

All right. So the use of traditional storage data is introduced here, because there are really a lot of other ways to use, and it is not our main character today. Next. Let's take a look at today's surprises and learn how to use Litepal for database storage operations.

Storing data using Litepal

The storage-related APIs in Litepal are in fact not much. But the use of the method is quite rich. And compared to the traditional insert () method. Using Litepal to store data can be as simple as to amaze you, so today we'll take a complete look at how Litepal stores 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 make the corresponding table own initiative to create.

Now look at these entity classes. We have found that these classes have no inheritance structure. Yes, because Litepal does not require these entity classes to have any inheritance structure for table management operations, it was not written for the sake of simplicity. However, the crud operation is not. Litepal requires all of the entity classes to inherit from the Datasupport class. So here we are going to add the inheritance structure to the line. Change the code of the News class. For example, see the following:

public class News extends datasupport{......//self-generated GET, set method}
Can see that this is just to let the news class inherit from the Datasupport, 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, so if you want to store a piece of data in the news table, you can write:

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 easy, do not need sqlitedatabase. No need to contentvalues, no need to assemble data by column name. Even if you don't need to specify a table name, you just need to create a new news object. Then the data to be stored through the setter method passed in, and finally call the Save () method is good. The Save () method is naturally inherited from the Datasupport class.

Besides. The Save () method still has a return value. We can infer whether the storage was successful based on the return value. For example, write this:

if (News.save ()) {Toast.maketext (context, "Storage succeeded", Toast.length_short). Show ();} else {Toast.maketext (context, "Storage failed", Toast.length_short). Show ();}
It can be seen that the Save () method returns a Boolean value that indicates whether the store succeeded or failed, but at the same time it was stated that the method would 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, such as the following:

News news = new News ("This is a news headline"), News.setcontent ("This is a news content"); News.setpublishdate (new Date ()); news.settitle; News.savethrows ();
Use the Savethrows () method to store data and throw a Datasupportexception exception if the store fails. We were able to handle the failure of the store by capturing the exception.

That some attentive friend might have noticed. Use the Insert () method to store data when there is a return value. Returns the corresponding ID of the inserted row. But the Save () method in Litepal returns a Boolean value, so how can we get the corresponding ID of this data after the store succeeds? About it. Litepal used a very ingenious approach. Do you remember that we defined an ID field in each entity class? When the Save () method is called or the Savethrows () method is stored successfully. Litepal will voluntarily assign the corresponding ID of the data to the ID field of the entity class. Let's do an experiment. The code looks like the following:

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, for example, as seen in the following:


Ok. The ID that was printed before save is 0, which indicates that the ID field has not been assigned yet 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, for example, as seen in:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvz3vvbglux2jsb2c=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "/>

Can see that the news has indeed been stored successfully, and the corresponding ID is 1. The results are consistent with those printed in front of us.

Just Litepal's storage function shows that there are more than just these use methods, in fact. Litepal in the storage of data silently help us do a lot of things, for example, there is a correlation between the various entity classes, we do not need to consider how to store data when the relationship between data and data, because litepal everything to help us do.

Let's take a look at some of the many-to-one relationships between comment and news, which can include multiple comments in a news message, 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 you just added to the news commentlist list before storing the news. This means that the two comment belong to this news object. Finally, the news is stored in the database, so that the relationship between them will be built on their own initiative. Let's look at the database table and check the news table first. For example, see the following:


OK, the second piece of news has been successfully saved to the news list. The ID of this news is 2. So where can we see the correlation? We learned in the previous article, many to one association when the foreign key is stored in the multi-party, so the correlation relationship we have to go to the comment table to see. For example, see the following:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvz3vvbglux2jsb2c=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast "/>

Can see that two comments have been successfully stored in the comment table. And the news_id of these two comments are all 2, indicating that they belong to the second piece of news. How, the relationship between the data is established by establishing the relationships between the entity classes before storing the data, and then invoking the Save () method. Isn't it very easy? The above code is just a multi-to-one use of the situation, another pair of one and many to many cases, the use of the method is almost the same, I believe you have been able to extrapolate.

In addition, Litepal provides a special method for storing collection data. Let's say we have a news collection. So how do you store every news in this collection? Traditionally, the ability to write:

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 kind of writing is of course possible. However, the efficiency is lower, because the Save () method is called in addition to running the storage operation. It also analyzes the relationship of the news class, so it is obviously time-consuming to analyze the correlation relationship again and again. Therefore, Litepal provides a SaveAll () method that is designed to store collection data. Use the method as seen below:

List<news> newslist; Datasupport.saveall (newslist);
The SaveAll () method receives a collection set of parameters. Just pass in the collection data to be stored. This method can complete the same function as the above code, but it is much more efficient and easier to write.

OK, so we've learned all the ways to use the storage operations provided in Litepal. So today's article is here. The next article will start by explaining how to use the update and delete operations. Interested friends please continue to read the Android database Master cheats (vi)--litepal changes and delete operations .

Litepal Open Source project address: Https://github.com/LitePalFramework/LitePal

The first time to get a blog update reminder. And a lot of other technical information to share, welcome to follow my public number, sweep the QR code below or search number Guolin_blog. You can focus on it.

Android database Master cheats (v)--litepal storage operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.