Litepal--android Database Framework Complete User manual

Source: Internet
Author: User

Litepal for Android

Litepal is an open source Android library that makes it easy for developers to use SQLite databases. You can do most of the database operations without writing any SQL statements, including creating or upgrading tables, adding, deleting, changing, checking, summing functions, and so on. The Litepal is also easy to set up, and you can integrate it into your project in just 5 minutes.

Start the experience now!

Function
    • Use object-relational mapping (ORM) mode.
    • Almost 0 configurations (only one profile, with very few property values).
    • Automatically maintains all data tables (for example, create, change, or delete tables).
    • Multi-database support
    • Encapsulates a variety of APIs and is a developer who avoids the hassle of writing SQL statements.
    • A very useful query API.
    • You can still write SQL statements, but packaged APIs are much more convenient and quick to use.
    • More features, please look forward to.
Download the latest version
    • Litepal-1.5.1.jar (contains *.class files in the library)
    • Litepal-1.5.1-src.jar (contains *.class files and *.java files in the library)
Quick Configuration 1. Import library using Eclipse
    • Download the latest jar in the section above. or browse all versions and select a download.
    • Place the jar file in the Libs directory of your Android project.
Using Android Studio

To edit your Build.gradle file, add the following dependencies:

Dependencies {    ' org.litepal.android:core:1.5.1 '}
2. Configure Litepal.xml

Create a "assets" directory in your project and create a "litepal.xml" file in it, and copy the code below.

<?XML version= "1.0" encoding= "Utf-8"?><Litepal>    <!--Define The database name of your application.         By default each database name should is end with. db.        If you didn ' t name your database end with a. db, Litepal would plus the suffix automatically for you. For example: <dbname value= "Demo"/> -    <dbnamevalue= "Demo" />    <!--Define The version of your database.        Each of the want to upgrade your database, the version tag would helps. Modify the models you defined in the mapping tags, and just make the version value plus one, the upgrade of Databas            E'll be processed automatically without concern. For example: <version value= "1"/> -    <versionvalue= "1" />    <!--Define your models in the list with mapping tag, Litepal would create tables for each mapping class.        The supported fields defined in models'll be mapped into columns. For example: <list> <mapping class= "Com.test.model.Reader"/> <mapping CLA ss= "Com.test.model.Magazine"/> </list> -    <List>    </List>        <!--Define where the. db file should is. "Internal" means the. db file is stored in the database folder of internal storage which no one can ACC Ess. "External" means the. db file is stored in the path to the directory on the primary external storage device WH Ere the application can place persistent files it owns which everyone can access.        "Internal" would act as default. For example: <storage value= "external"/> -    </Litepal>

This is the only configuration file, and the properties you want to configure are very simple.

    • dbname Configuring the Project database name
    • Version number of the configuration database. Each time you update the library, add one to its value.
    • List configuration mapping class.
    • Storage the location where the configuration database files are stored. The value is "internal" or "external".
3. Configure Litepalapplication

You don't have to pass the context parameter. To make the API simple, you simply configure litepalapplication in Anandmanmanestest.xml, as follows:

< Manifest >    < Application         Android:name = "Org.litepal.LitePalApplication"         ...     >         ...     </ Application > </ Manifest >

Of course, you may already have your own application configured here, such as:

< Manifest >    < Application         Android:name = "Com.example.MyOwnApplication"         ...     >         ...     </ Application > </ Manifest >

It doesn't matter, Litepal can accept it. Just call Litepal.initialize (context) in your program:

 Public class extends anotherapplication {    @Override    publicvoid  onCreate () {        super  . OnCreate ();        Litepal.initialize (this);    }    ...}

Make sure to call this method as early as possible. It is best to call it in the OnCreate () method. And always remember to use the application context as a parameter. Do not use any activity or service instance as a parameter, or a memory leak may occur.

Start using

Once the configuration is successful, you can use these powerful methods.

1. Create a data table

First build a model. For example, you want to build two models of album and song. Can be defined as follows:

 Public classAlbumextendsDatasupport {@Column (unique=true, DefaultValue = "Unknown")    PrivateString name; Private floatPrice ; Private byte[] cover; Privatelist<song> songs =NewArraylist<song>(); //generated getters and setters.    ...} Public classSongextendsDatasupport {@Column (nullable=false)    PrivateString name; Private intduration; @Column (Ignore=true)    PrivateString Uselessfield; PrivateAlbum Album; //generated getters and setters.    ...}

These models are then added to the Litepal.xml map list:

< List >    <  class= "Org.litepal.litepalsample.model.Album"/>    <  class= "Org.litepal.litepalsample.model.Song"/></ List >

Good! The data table is created automatically the next time you manipulate the database. For example, get sqlitedatabase using the following code:

Sqlitedatabase db = Litepal.getdatabase ();

Now these tables will automatically generate SQL statements such as the following:

CREATE TABLEAlbum (IDinteger Primary KeyAutoIncrement, nametext Unique default 'Unknown', PriceReal, cover blob);CREATE TABLESong (IDinteger Primary KeyAutoIncrement, nametext  not NULL, Durationinteger, album_idinteger);
2. Updating data sheets

It's also very easy to update the data table with Litepal, just by modifying the instance model to the data you want:

 Public classAlbumextendsDatasupport {@Column (unique=true, DefaultValue = "Unknown")    PrivateString name; @Column (Ignore=true)    Private floatPrice ; Private byte[] cover; PrivateDate ReleaseDate; Privatelist<song> songs =NewArraylist<song>(); //generated getters and setters.    ...}

The ReleaseDate field has been added and the Price field has been commented. Then increase the version number in Litepal.xml:

<!--     Define The version of your database. Each     of the want to upgrade your database, the version tag would helps.    Modify the models you defined in the mapping tags, and just make the     version value plus one, the upgrade of Database
    will be processed automatically without concern.    For example:        <version value= "1" ></version><   Value= "2"></version>

The data table will be updated automatically the next time you manipulate the database. The ReleaseDate column will be added to the album table, and the price column will be dropped. In addition to the columns that are deleted in the album table, the other data is still present.

However, for some upgrade conditions that Litepal cannot handle, all data in the upgrade table will be cleared:

    • Add a field with a comment of unique = true.
    • Change the comment for the field to unique = True.
    • Change the comment for the field to Nullable = False.

Note the above-mentioned situation that results in data loss.

3. Save your data

The API for saving data is object-oriented. Each model inherited from Datasupport can use the Save () method to hold the data:

New Album (); Album.setname ("Album"); Album.setprice (10.99fnew  Song (); Song1.setname("song1"); song1.setduration("Thenew  Song (); Song2.setname (" Song2 "); Song2.setduration (356); Song2.setalbum (album); Song2.save () ;

The above Operation inserts album, Song1 and Song2 into the database and associates them.

4. Updating data

The simplest way to do this is to first find the record to be updated with the Find () method and use the Save () method to update the data:

Album albumtoupdate = Datasupport.find (Album.  Class, 1); Albumtoupdate.setprice (//  raiseThe Price Albumtoupdate.save ();

Any module that integrates the Datasupport class has an update () and a updateAll () of two methods. You can update a single record with the specified ID:

New Album (); Albumtoupdate.setprice (//  raiseThe price albumtoupdate.update (ID);

Or you can update multiple records with a Where condition:

New Album (); Albumtoupdate.setprice (//  raiseThe price albumtoupdate.updateall ("name =?", " Album ");
5. Delete data

You can delete a single record using the static method of Delete () in the Datasupport class:

Datasupport.delete (Song.  Class, id);

or delete multiple records using DELETEALL ():

Datasupport.deleteall (Song.  Class, "duration >?", "350");
6. Querying data

To query a single record by specifying an ID:

Song song = Datasupport.find (song.  Class, id);

To query all records in a table:

list<song> allsongs = Datasupport.findall (Song.  Class);

Use the API to build complex queries:

list<song> songs = Datasupport.where ("Name like?", "song%"). Order ("duration"). Find (Song.  Class);
7. Asynchronous operations

By default, each database operation is on the main thread. If your operation may take a long time, such as saving or querying a large number of records. You may need to use asynchronous operations.

Litepal supports all asynchronous operations for adding, deleting, changing, and checking methods. If you want to find all the records from the song table of the background thread, use the following code:

Datasupport.findallasync (Song.  Class). Listen (new  findmulticallback () {    @Override    publicvoid OnFinish (list<t> t) {        List<Song> allsongs = (list<song>) t;    }});

Simply use Findallasync () instead of findAll () and attach a listen () method, and once the operation is complete, the lookup results will be recalled to the OnFinish () method.

Abd asynchronous save is exactly the same:

New Album (); Album.setname ("Album"); Album.setprice (10.99f); Album.setcover (Getcoverimagebytes ( ); Album.saveasync (). Listen (new  savecallback () {    @Override    public  void OnFinish (boolean  success) {    }});

Simply use Saveasync () instead of Save (). It will save the album asynchronously to the database, and the saved result will be recalled to the OnFinish () method.

8. Multiple databases

If your app requires multiple databases, Litepal fully supports it. You can create any number of databases at run time. For example:

New Litepaldb ("Demo2", 1); Litepaldb.addclassname (Singer. class . GetName ()); Litepaldb.addclassname (Album. class . GetName ()); Litepaldb.addclassname (Song. class . GetName ()); Litepal.use (LITEPALDB);

This will create a DEMO2 database with Singer,album and song tables.

If you only want to create a new database that is identical to the Litepal.xml configuration, you can use the following command:

Litepaldb litepaldb = Litepaldb.fromdefault ("newdb"); Litepal.use (LITEPALDB);

You can switch back to the default database at any time:

Litepal.usedefault ();

You can delete any database by specifying the database name:

Litepal.deletedatabase ("newdb");

Litepal--android Database Framework full user manual

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.