Android database Master cheats (vi)--litepal modification and deletion operations

Source: Internet
Author: User
Tags first string

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

In the previous article, we learned to use Litepal to store data. Indeed, it is significantly simpler and more convenient than using Android native Api,litepal directly. Then, in the Add and remove changes to check four operations, we have to "increase" the study finished, today let us continue the strike, learn how to use Litepal to modify and delete operations. Have not read the previous article of the friend suggested first to refer to the Android database Master cheats (v)--litepal storage operations .

Litepal's project address is:https://github.com/LitePalFramework/LitePal

Traditional ways to modify and delete data

As we have learned in the previous article, an insert () method is provided in the Sqlitedatabase class for inserting data, and similarly, it provides both the update () and delete () methods, respectively, for modifying and deleting data. First look at the method definition of the update () method:

public int update (string table, contentvalues values, String whereclause, string[] whereargs)
The update () method receives four parameters, the first parameter is the table name, the second parameter is a Contentvalues object that encapsulates the data to be modified, and the third and fourth parameters specify which rows to modify, corresponding to the where part of the SQL statement.

So for example, if we want to change the title of the record with ID 2 in the News list to "IPhone6 today," You can write:

Sqlitedatabase db = Dbhelper.getwritabledatabase (); Contentvalues values = new Contentvalues () values.put ("title", "Today IPhone6 release");d b.update ("News", values, "id =?", New STR Ing[] {"2"});

The function is equivalent to the following SQL statement:

Update news set title= ' IPhone6 released today ' where id=2;
As you can see, the update () method is significantly more semantically and easier to understand than using SQL statements directly.

Then look at the method definition of the Delete () method:

public int Delete (string table, String Whereclause, string[] whereargs)
The delete () method receives three parameters, the first parameter is also the table name, and the second and third parameters specify which rows to delete, corresponding to the where part of the SQL statement.

So for example, if we want to delete all the news that we haven't commented on, we can write it like this:

Sqlitedatabase db = Dbhelper.getwritabledatabase ();d b.delete ("News", "Commentcount =?", new string[] {"0"});
The function is equivalent to the following SQL statement:
Delete from news where commentcount=0;

This shows that Android provides us with these help methods, to a large extent, it does simplify the complexity of many database operations. But Litepal obviously did a better job, let's learn how to use Litepal to modify and delete operations.

modifying Data using Litepal

Litepal the API to modify the data is relatively simple, and there is not much use, but also better understanding, methods are defined in the Datasupport class, we first look at the method definition:

public static int update (class<?> modelclass, contentvalues values, long ID)
This static update () method receives three parameters, the first parameter is class, passing in the class that we want to modify, the second argument is the Contentvalues object, the three parameter is a specified ID, which indicates which row of data we want to modify.

So for example, if we want to change the title of the record with ID 2 in the News list to "IPhone6 today," You can write:

Contentvalues values = new Contentvalues (), Values.put ("title", "Today's IPhone6 release");D atasupport.update (News.class, values, 2);
As you can see, the overall is still more simple than the native usage, first we avoid the steps to get the Sqlitedatabase object, and secondly, when you specify that you want to modify an ID record, you only need to pass in the ID, and the syntax is more concise.

Then some friends may ask, maybe I want to modify all the data under a certain condition, instead of just modifying the data of an ID, what should I do? Don't worry, Litepal also provides another easy way to define the method as follows:

public static int UpdateAll (class<?> modelclass, contentvalues values, String ... conditions)
The UpdateAll () method represents modifying multiple rows of records, where the first parameter is still class, the second argument is a Contentvalues object, and the third parameter is an conditions array that specifies which rows to modify for the constraint. The return value indicates how many rows of data this modification affects.

So for example, if we want to change the title of all news headlines titled "Today IPhone6 Release" to "Today's IPhone6 plus release", you can write:

Contentvalues values = new Contentvalues (), Values.put ("title", "Today IPhone6 plus release");D Atasupport.updateall (News.class, Values, "title =?", "IPhone6 released today");
There's nothing left to say, but let's take a look at the last conditions array, because its type is a string array, we can fill in any number of string arguments here, where the first string parameter is used to specify the constraints, All of the following string parameters are used to populate the placeholder (i.e., the number) in the constraint, such as a placeholder in the constraint, then a parameter should be filled in, and if there are two placeholders, you should fill in the two parameters later, and so on.

For example, if we want to change the title of all news headlines titled "Today IPhone6 released" and the number of comments greater than 0 to "today's IPhone6 plus release", you can write:

Contentvalues values = new Contentvalues (), Values.put ("title", "Today IPhone6 plus release");D Atasupport.updateall (News.class, Values, "title =?" and Commentcount >? "," IPhone6 released Today "," 0 ");
As you can see, it is significantly easier to implement conditional constraints in a placeholder way than native APIs.

So what should we do if we want to change the headline of all news headlines to "Today's IPhone6 release"? In fact, this is much simpler, just remove the last constraint, as shown below:

Contentvalues values = new Contentvalues (), Values.put ("title", "Today IPhone6 plus release");D Atasupport.updateall (News.class, values);
How about this writing is not sense of semantics is very strong? The UpdateAll () method modifies all rows of data without specifying a constraint, indeed the update all.

Of course some friends may feel that this is still a bit complicated to use, because this Contentvalues object is very annoying, each time you create it to write a lot of tedious code. It doesn't matter, Litepal also fully consider this situation, provide a way to modify the data without contentvalues, we try to use this new method to accomplish the same function.

For example, the title of the record with ID 2 in the news table is changed to "Today IPhone6 release", it can be written as follows:

News updatenews = new News (); Updatenews.settitle ("IPhone6 released today"); Updatenews.update (2);
This time we did not use the contentvalues, but new out a news object, the data to be modified directly into the set, and finally call the update () method and pass in the ID can be. Not only does the Contentvalues object not be created, the table name is not specified, because the news object defaults to the modified news table.

This is one of the uses, so if we want to change the title of all news headlines "today IPhone6 released" and the number of comments greater than 0 to "Today IPhone6 plus release", you can write:

News updatenews = new News (); Updatenews.settitle ("IPhone6 released today"); Updatenews.updateall ("title =? and Commentcount >? "," IPhone6 released Today "," 0 ");
Still very well understood, here I will no longer explain in detail.

But this usage has a point to note that if we want to change a piece of data to a default value, such as changing the number of comments to 0, just call Updatenews.setcommentcount (0) so that it cannot be modified successfully, because even if this line of code is not called, The value of Commentcount is also 0 by default. So if you want to modify the data of a column to a default value, you also need to use the Settodefault () method. The usage is also simple, passing in the Settodefault () method The name of the field to be modified (the field name in the Class), for example, if we want to zero the number of comments on all news in the information table, we can write:

News updatenews = new News (); Updatenews.settodefault ("Commentcount"); Updatenews.updateall ();
Using Litepal to delete data

Litepal the API to delete data is similar to modifying data, but it's much simpler, let's take a look at the method definition in the Datasupport class as follows:

public static int Delete (class<?> modelclass, long ID)
The delete () method receives two parameters, the first parameter is class, the class is passed in to the one we want to delete, and the second parameter is a specified ID that indicates which row of data we want to delete.

So for example, if we want to delete the record with ID 2 in the News table, we can write this:

Datasupport.delete (News.class, 2);

It is important to note that this will not only delete the record with ID 2 in the news table, but also delete the record in the other table with the news ID 2 as the foreign key, since the foreign key does not exist, so the data is meaningless.

It may be a bit of a mouthful, let's take a look at it for example. For example, there are currently two data in the news table, as shown in:


Then there are two data in the comment table, as shown in:


Where the foreign keys of the two data in the comment table are 2, the record that points to the news table with the ID 2. So below we execute the following DELETE statement:

int deletecount = Datasupport.delete (News.class, 2); LOG.D ("TAG", "delete Count is" + deletecount);
Where the return value of the Delete () method represents the number of records that were deleted, the printing results are as follows:


As you can see, three records have been deleted, so let's go to the news list and check it out:


OK, there is only one record left, and the record with ID 2 is actually deleted. Then look at the comment table, as shown in:


The data's all gone! Why is it? Since the two data in the comment table is a foreign key with the data in the news table with ID 2, and now the foreign key does not exist, there is no natural meaning for the two data, so the number of records deleted is altogether 3. Is it good to understand a lot of it?

In addition to deleting data of the specified ID, Datasupport also provides a way to bulk delete data through a where statement, first look at the method definition:

public static int DeleteAll (class<?> modelclass, String ... conditions)
Looks familiar, doesn't it? Very simple, the DeleteAll () method receives two parameters, the first parameter is class, passing in the class that we want to delete, the second parameter is a conditions array, which specifies the constraints of which rows are deleted, and the return value indicates how many rows of data were deleted. The usage and UpdateAll () methods are basically the same.

So for example, if we want to delete all the news that is titled "Today IPhone6 released" and the number of comments equals 0, you can write:

Datasupport.deleteall (News.class, "title =?") and Commentcount =? "," IPhone6 released Today "," 0 ");
And if we want to remove all the data from the news list, we can write it like this:
Datasupport.deleteall (News.class);
Without specifying a constraint, the DeleteAll () method deletes all the data in the table.

In addition to the static Delete method provided in the Datasupport class, there is a Delete method that acts on the object, that is, any instance that inherits from the Datasupport class can delete the data by calling the Delete () instance method. But only if the object must be persisted, a non-persisted object will have no effect if the delete () method is called.

For example, the following is the wording:

News news = new News (); News.delete ();
Here new has a news object, which is obviously not persisted, then calling the Delete () method does not delete any data.

But if we have persisted this object before, then calling the Delete () method will delete the object's corresponding data, for example:

News news = new News ("This is a news headline"), News.setcontent ("This is a news content"), News.save ();.. news.delete ();
An object if the save is over, it is persistent. In addition to calling the Save () method, the objects that are identified from the database through the query method provided in Datasupport are also persisted, and the function of the query is explained in the next blog post.

There is also a simple way to help us determine if an object is persisted, and a issaved () method is provided in the Datasupport class, which returns true to indicate that the object is persisted and that returning false indicates that the object is not persisted. Then delete the corresponding data of an object can also be written as follows:

News News;...if (news.issaved ()) {News.delete ();}

Well, so that we have to litepal in the use of the modification and deletion of data operations are basically finished, then today's article here, the next article will begin to explain the use of query data.

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

Android database Master cheats (vi)--litepal modification and deletion 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.