Android Data Storage--open source Litepal method operation database

Source: Internet
Author: User

One configuration Litepal

1. Add dependencies in the dependencies closure in App/build.gradle:

' org.litepal.android:core:1.4.1 '

2. In the App/src/mian directory, new directory, named the assets directory, creates a file in the directory, naming Litepal.xml. and make edits:

 1  <?xml version= " 1.0  "  encoding=" Span style= "COLOR: #800000" >utf-8   "? >2  <litepal>3  <dbname value= "  bookstore   " ></dbname>< Span style= "COLOR: #008080" >4  5  <version value="  1   " ></version>< Span style= "COLOR: #008080" >6  <list>7  8  </list>9  </litepal> 

The dbname is used to specify the database name, and version specifies the revision number.

3. Configure litepalapplication, modify the code in the Androidmainactivity, add in <application>:

Android:name="org.litepal.LitePalApplication"

Two creating and Upgrading databases

In Litepal, the object-relational mapping model can be used to write the database using object-oriented thinking, that is, the table is mapped to the corresponding class, the columns in the table are the data types in the class, and the corresponding get and set methods are written to the various data.

(1) Create a database:

If you create a book table first, create a book class. As follows:

1  Public classBook {2 3     Private intID;4     PrivateString author;5     Private DoublePrice ;6     Private intpages;7     PrivateString name;8 9      Public intgetId () {Ten         returnID; One     } A  -      Public voidSetId (intID) { -          This. ID =ID; the     } -  -      PublicString Getauthor () { -         returnauthor; +     } -  +      Public voidSetauthor (String author) { A          This. Author =author; at     } -  -      Public DoubleGetPrice () { -         returnPrice ; -     } -  in      Public voidSetprice (DoublePrice ) { -          This. Price =Price ; to     } +  -      Public intgetpages () { the         returnpages; *     } $ Panax Notoginseng      Public voidSetpages (intpages) { -          This. Pages =pages; the     } +  A      PublicString GetName () { the         returnname; +     } -  $      Public voidsetName (String name) { $          This. Name =name; -     } -}

In the book class, we define the fields for each column in the corresponding table in the class. This is the mapping.

Add the book class to the list of mapping models and modify the code in Litepal.xml as follows: Note Be sure to write the full class name.

    <list>        Class="com.example.litepaltest.Book"></mapping>    </list>

Now as soon as any database operation is performed, the database is created and the Book table is created, so the simplest database operation is done using the Litepal.getdatabase () method to create the database and table.

(2) Upgrade the database:

Before using Sqliteopenhelper for database operations, although you can also upgrade, each upgrade will first delete the previous table, if there is data stored in the table will cause unnecessary loss. Using Litepal does not delete the previously existing tables and data at the time of the update.

If we add a new column to the Book table, just add a new field and a corresponding method to the class. The code is as follows:

 1  private   String Press;  2  3  public< /span> String getpress () { 4  return   press;  5  }  6  7  public  void   setpress (String press) { 8  this . Press = press;  9 } 

You can also add a new table category table to classify the books. Create a new category class, and the same field corresponds to the corresponding row, as follows:

1  Public classCategory {2     Private intID;3     PrivateString CategoryName;4     Private intCategorycode;5 6      Public intgetId () {7         returnID;8     }9 Ten      Public voidSetId (intID) { One          This. ID =ID; A     } -  -      Public voidsetcategoryname (String CategoryName) { the          This. CategoryName =CategoryName; -     } -  -      Public voidSetcategorycode (intCategorycode) { +          This. Categorycode =Categorycode; -     } +}

At this point, you only need to modify the corresponding version number in Litepal.xml and add the class name of the newly added table. (The version number is increased to 2)

1<litepal>2<dbname value="Bookstore"></dbname>3 4<version value="2"></version>5<list>6<mappingclass="Com.example.litepaltest.Book"></mapping>7<mappingclass="com.example.litepaltest.Category"></mapping>8</list>9</litepal>

Three Add data

Adding data is simple, just the table you want to add inherits from the Litepalsupport class (the original inherited Datasupport class, which is now deprecated ).

 Public class Book extends Litepalsupport

Then add the relevant data to the mainactivity and save it with Save (). As follows:

1Button AddData =(Button) Findviewbyid (r.id.add_data);2Adddata.setonclicklistener (NewView.onclicklistener () {3 @Override4              Public voidOnClick (view view) {5Book book =NewBook ();6Book.setname ("The da Wei");7Book.setauthor ("Mask");8Book.setpages ( -);9Book.setprice (19.33);TenBook.setpress ("unkonw"); One Book.save (); A             } -});

As above, first create an instance of the book, then call the Set method in the book class to set the data, and then use the Save () method to save the data.

Four Update data

We modify the price of a book in the table and the publisher, which has the limitations of the author and title. The code is as follows:

1Button UpdateData =(Button) Findviewbyid (r.id.update_data);2Updatedata.setonclicklistener (NewView.onclicklistener () {3 @Override4              Public voidOnClick (view view) {5Book book =NewBook ();6Book.setprice (14.99);7Book.setpress ("Auchor");8Book.updateall ("name= and author=?","The a","MASKD");9             }Ten});

The table is instantiated and then modified by the set to update the data to be updated by the UpdateAll () method, where the first parameter is the condition of the restriction, followed by the constraint-specific parameters. If you do not specify a conditional statement, all data is updated.

If you want to update the contents of a column to a default value, use the following code: You can set the value in the target column to the default value.

Book.settodefault ("pages");

Five Delete data

Delete data assumption or inherit from Datasupport class: The code is as follows

1Button DeleteButton =(Button) Findviewbyid (r.id.delete_data);2Deletebutton.setonclicklistener (NewView.onclicklistener () {3 @Override4              Public voidOnClick (view view) {6Datasupport.deleteall (book.class,"price<?","12.00");7             }8});

Where delete Deletes the DeleteAll method The first parameter is the corresponding table, the second and third parameters correspond to where in the SQL statement and the corresponding numeric value.

Android Data Storage--open source Litepal method operation database

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.