Android Database Expert (6)-modification and deletion of LitePal, androidlitepal

Source: Internet
Author: User

Android Database Expert (6)-modification and deletion of LitePal, androidlitepal

Reprinted please indicate the source: http://blog.csdn.net/guolin_blog/article/details/40083685

In the previous article, we learned how to use LitePal to store data. Indeed, LitePal is much easier and easier than directly using Android native APIs. In addition, we have completed adding, deleting, modifying, and querying operations. Today, let's continue to learn how to use LitePal for modification and deletion. If you have not read the previous article, please refer to it first.Android database experts (5)-LitePal storage operations.

The Project address of LitePal is:Https://github.com/LitePalFramework/LitePal

Traditional data modification and deletion Methods

We have learned in the previous article that the SQLiteDatabase class provides an insert () method for data insertion. Similarly, it also provides the update () and delete () methods, modify and delete data respectively. Let's take a 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 are used to specify which rows to modify, corresponds to the where section in the SQL statement.

For example, if we want to change the title of the record with id 2 in the news table to "Today's iPhone6 release", we can write it like this:

SQLiteDatabase db = dbHelper. getWritableDatabase (); ContentValues values = new ContentValues (); values. put ("title", "iPhone 6 released today"); db. update ("news", values, "id =? ", New String [] {" 2 "});

The function is equivalent to the following SQL statement:

Update news set title = 'today's iPhone6 release' where id = 2;
We can see that the update () method is more semantic and easier to understand than directly using SQL statements.

Next, let's look at the 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 are used to specify which rows to delete, corresponding to the where part of the SQL statement.

For example, if we want to delete all news without comments in the news table, we can write it like this:

SQLiteDatabase db = dbHelper.getWritableDatabase();db.delete("news", "commentcount = ?", new String[] {"0"});
The function is equivalent to the following SQL statement:
delete from news where commentcount=0;

It can be seen that the help methods provided by Android have greatly simplified the complexity of many database operations. However, LitePal is obviously better. Let's take a look at how to use LitePal for modification and deletion.

Use LitePal to modify data

LitePal's APIs for data modification are relatively simple, and there are no too many usage methods. The methods are all defined in the DataSupport class. Let's 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. It is good to pass in the Class of the Class we want to modify. The second parameter is the ContentValues object, the three parameters are a specified id, indicating the row of data to be modified.

For example, if we want to change the title of the record with id 2 in the news table to "Today's iPhone6 release", we can write it like this:

ContentValues values = new ContentValues (); values. put ("title", "released on iPhone 6"); DataSupport. update (News. class, values, 2 );
It can be seen that, in general, it is simpler than the native usage. First, we should avoid the steps to obtain the SQLiteDatabase object, second, you only need to input this id when specifying to modify an id record. The syntax is more concise.

Some may ask, what should I do if I want to modify all the data under a certain condition instead of modifying the data of a specific id? Don't worry, LitePal also provides another simple method, which is defined as follows:

public static int updateAll(Class<?> modelClass, ContentValues values, String... conditions)
The updateAll () method indicates modifying a multi-row record. The first parameter is still a Class, the second parameter is a ContentValues object, and the third parameter is a conditions array, it is used to specify the row constraints to be modified. The returned value indicates the number of rows affected by this modification.

For example, if we want to change the title of all the news in the news table titled "Today's iPhone6 release" to "Today's iPhone6 Plus release", we can write it like this:

ContentValues values = new ContentValues (); values. put ("title", "released on iPhone6 Plus"); DataSupport. updateAll (News. class, values, "title =? "," Released on iPhone 6 today ");
I have nothing to say before. Let's take a look at the final conditions array. Because its type is a String array, We can enter any number of String parameters here, the first String parameter is used to specify the constraints, and all the subsequent String parameters are used to fill the placeholders in the constraints (that is? For example, if there is a placeholder in the constraints, you should enter a parameter later. If there are two placeholders, you should enter two parameters later, and so on.

For example, if we want to change the title of all news headlines with the title "released on iPhone 6 today" and the number of comments greater than 0 to "released on iPhone 6 Plus today", we can write it like this:

ContentValues values = new ContentValues (); values. put ("title", "released on iPhone6 Plus"); DataSupport. updateAll (News. class, values, "title =? And commentcount>? "," IPhone 6 released today "," 0 ");
It can be seen that conditional constraints through Placeholders are much easier to implement than native APIs.

So if we want to change the title of all news in the news table to "Today's iPhone6 release", how should we write it? In fact, this is simpler. You only need to remove the final constraints, as shown below:

ContentValues values = new ContentValues (); values. put ("title", "released on iPhone6 Plus"); DataSupport. updateAll (News. class, values );
How about this writing method? Does it feel very semantic? The updateAll () method modifies the data of all rows without specifying constraints. It is indeed update all.

Of course, some friends may think it is still a bit complicated to use, because this ContentValues object is very annoying and requires a lot of tedious code every time you create it. It doesn't matter. LitePal also takes this situation into full consideration and provides a method to modify data without ContentValues. Next we will try to use this new method to complete the above functions.

For example, if you change the title of the record whose id is 2 in the news table to "Today's iPhone6 release", you can write it like this:

News updateNews = new News (); updateNews. setTitle ("released on iPhone 6 today"); updateNews. update (2 );
This time, we didn't use ContentValues. Instead, we produced a new News object, directly set the data to be modified, and finally called the update () method and passed in the id. You do not need to create a ContentValues object or specify a table name because the News object is the modified news table by default.

This is one of the usage. If we want to change the title of all news topics with the title "Today's iPhone6 release" and the number of comments greater than 0 to "Today's iPhone6 Plus release ", you can write it like this:

News updateNews = new News (); updateNews. setTitle ("released on iPhone 6 today"); updateNews. updateAll ("title =? And commentcount>? "," IPhone 6 released today "," 0 ");
I am not going to explain it in detail here.

However, you must note that if you want to change a piece of data to the default value, for example, to change the number of comments to 0, you only need to call updateNews. setCommentCount (0) cannot be modified successfully because the value of commentCount is 0 by default even if this line of code is not called. Therefore, if you want to change the data of a column to the default value, you also need to use the setToDefault () method. The usage is also very simple. You can input the field name to be modified in the setToDefault () method (the Field name in the class). For example, we want to clear the comments of all news in the news table, you can write it like this:

News updateNews = new News();updateNews.setToDefault("commentCount");updateNews.updateAll();
Use LitePal to delete data

LitePal's data deletion API is similar to modifying data, but it is simpler. Let's take a look at the method definition in the DataSupport class, as shown below:

public static int delete(Class<?> modelClass, long id)
The delete () method receives two parameters. The first parameter is Class. It is good to input the Class of the Class to be deleted. The second parameter is a specified id, indicates the row of data to be deleted.

For example, if we want to delete the record with id 2 in the news table, we can write it like this:

DataSupport.delete(News.class, 2);

Note that this will not only delete the records whose id is 2 in the news table, at the same time, the record with news id 2 in other tables will be deleted as the data of the foreign key, because the foreign key does not exist, so the data will not be reserved.

It may be a bit difficult to say. Let's take an example. For example, the news table currently has two data items, as shown in:


The comment table also contains two data items, as shown in:


The Foreign keys of the two data items in the comment table are both 2, pointing to the record with id 2 in the news table. Then, execute the following Delete statement:

int deleteCount = DataSupport.delete(News.class, 2);Log.d("TAG", "delete count is " + deleteCount);
The Return Value of the delete () method indicates the number of deleted records. The printed result is as follows:


We can see that three records have been deleted, so we can query the news table again:


OK. There is only one record left. The record with id 2 is deleted. Go to the comment table and check it, as shown in:


No data! Why? Because the two data items in the comment table use the data with the id of 2 in the news table as the foreign key, and the foreign key does not exist, the two data items naturally do not exist, therefore, the total number of deleted records is three. Does that mean I understand a lot?

In addition to deleting data of the specified id, DataSupport also provides a method to delete data in batches using the where statement. Let's first look at the method definition:

public static int deleteAll(Class<?> modelClass, String... conditions)
Looks familiar, right? Very simple. The deleteAll () method receives two parameters. The first parameter is Class. It is good to input the Class of the Class we want to delete, and the second parameter is a conditions array, it is used to specify the constraints for deleting rows. The returned value indicates the number of rows deleted this time. The usage is basically the same as that of the updateAll () method.

For example, if we want to delete all the news in the news table titled "released on iPhone 6 today" with a comment value of 0, we can write it like this:

DataSupport. deleteAll (News. class, "title =? And commentcount =? "," IPhone 6 released today "," 0 ");
If we want to delete all the data in the news table, we can write as follows:
DataSupport.deleteAll(News.class);
If no constraints are specified, the deleteAll () method deletes all data in the table.

In addition to the static deletion method provided in the DataSupport class, there is also a deletion method acting on the object, that is, any instance inherited from the DataSupport class can call delete () this instance method is used to delete data. But the premise is that this object must be persistent. If a non-persistent object calls the delete () method, it will not produce any effect.

For example:

News news = new News();news.delete();
A new News object is generated here, which is obviously not persistent. Therefore, the delete () method is called to delete no data.

However, if we have persisted this object before, then calling the delete () method will delete the data corresponding to this object, for example:

News news = new News (); news. setTitle ("This is a news title"); news. setContent ("this is a piece of news"); news. save ();... news. delete ();
If an object is saved, it is persistent. In addition to calling the save () method, the objects found from the database through the query method provided in DataSupport are also persistent. The query function will be explained in the next blog.

There is also a simple way to help us determine whether an object is persistent. The DataSupport class provides an isSaved () method, if this method returns true, the object is persistent. If it returns false, the object is not persistent. You can delete the data corresponding to an object as follows:

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

Now, we have learned how to modify and delete data operations provided in LitePal, so today's article is here, the next article will explain how to query data.

LitePal open source project: https://github.com/LitePalFramework/LitePal




Related Article

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.