First Line Code Chapter 6 Data Storage Scheme - LitePal Database Storage

LitePal - An open source Android database framework.
It uses object-relational mapping (ORM) mode to encapsulate the common database functions in development, so that it can complete all kinds of table building, deletion and modification checking operations without writing SQL statements.

Use open source libraries in projects:
Most open source projects submit versions to jcenter, and we just need to declare the reference to the open source library in the app/build.gradle file.

LitePal project address: https://github.com/LitePalFramework/LitePal

Configuration of LitePal

1. Declare the open source library in the app/build.gradle file

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    testCompile 'junit:junit:4.12'
    compile 'org.litepal.android:core:1.6.0'
}

Just add this line: compile'org.litepal.android:core:1.6.0'
Among them, org.litepal.android:core is the fixed part; 1.6.0 is the meaning of version number.

2. Configure litepal.xml file
In the app src main directory, create a new asset directory, and then create a new litepal.xml file in the assets directory.
The contents of the litepal.xml file are as follows:

<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value="BookStore" />
    <version value="2" />
    <list>
        <mapping class="com.sky.litepaltest.Book" />
        <mapping class="com.sky.litepaltest.Watch" />
    </list>

</litepal>

Among them:
Tags are used to specify database names;
Tags are used to specify the database version number.
Labels are used to specify all mapping models.
Labels are used to declare the mapping model classes that need to be configured, and the full class name must be used here.

3. Configure Android Manifest. XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sky.litepaltest">

    <application
        android:name="org.litepal.LitePalApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Configure application to android:name= "org. litepal. LitePal Application" so that all LitePal functions work properly.

II. Creating and upgrading databases
1. Create a new class, define fields, and generate corresponding getter and setter methods.
The class defined here is the table in the database. So to add a new table, you just need to add a new class and add it to the list of mapping models.
The fields defined are each column in the table. So to add a column, you just need to add a field and generate the corresponding getter and setter methods.

Shortcut keys for generating getter and setter methods: Define the fields in the class first, then press Alt+Insert

2. Adding classes to the list of mapping models, i.e. labels in litepal.xml files

3. The database can be created by calling the Connector.getDatabase() method.

4. By modifying the version number of label b, the upgrade operation of database can be completed.

3. Operation of database - CRUD operation

To perform CRUD operations, the model class must inherit the DataSupport class, as follows

    public class Book extends DataSupport{
        .......
    }

1. Adding data
Create an instance of the model class, then call various setter() methods of the instance to set the data, and finally call the save() method of the instance.

    private void addData() {
        Book book = new Book();
        book.setName("Android");
        book.setAuthor("sky");
        book.setPages(201);
        book.setPrice(55.8);
        book.save();
    }

2. Update data
There are many ways to update. The simplest way to update is to reset the stored object and then call the save() method.

    private void updateData1() {
        Book book = new Book();
        book.setName("Android");
        book.setAuthor("sky");
        book.setPages(201);
        book.setPrice(55.8);
        book.save();
        book.setPrice(25.8);
        book.save();
    }

Mode 2: Use updateAll() method

    private void updateData2() {
        Book book = new Book();
        book.setPrice(25.8);
        book.updateAll("author=?", "demo");
    }

The updateData2() method has been updated to 25.8 for all Price s whose author is demo.
The updateAll() method updates all data if no conditional statement is specified.

    private void updateData3() {
        Book book = new Book();
        book.setToDefault("price");
        book.updateAll();
    }

The above code indicates that all prices are updated to the default value of 0.
setToDefault() updates the data to the default value.

3. Delete data
There are two main ways to delete data:
The first is to call the delete() method of the stored object directly.

    private void deleteData1() {
        Book book = new Book();
        book.setPrice(25.8);
        book.save();
        book.delete();
    }

Another is to use the deleteAll() method.

    private void deleteData2() {
        DataSupport.deleteAll(Book.class, "price < ?", "90");
    }

The above code indicates that all data in the Book table with a price below 90 is deleted.
The updateAll() method deletes all data in the table if no conditional statement is specified.

4. Query data
There are many interfaces for querying data

Query all data in the table - findAll() method.
List books = DataSupport.findAll(Book.class);
This method returns a List collection of class types so that the queried data can be traversed.

The first data in the query table - findFirst() method.
Book book = DataSupport.findFirst(Book.class);

findLast() method is the last data in the query table.
Book book = DataSupport.findLast(Book.class);

Additional query functions can also be customized by using linked queries

select() method to specify which columns of data to query
For example, look up only the data in the column name and author of the table:
List books = DataSupport.select("name","author").find(Book.class);

where() method to specify the constraints of the query
For example, in the query table, the price is more than 10:
List books = DataSupport.where("price>?","10").find(Book.class);

order() method to specify the sort of results
If the query results are sorted according to the price:
List books = DataSupport.order("pricre desc").find(Book.class);
desc means descending sort; asc or not writing means ascending sort

limit() method to specify the number of query results
For example, the first three data in the table are as follows:
List books = DataSupport.limit(3).find(Book.class);

offset() method to specify the offset of the query result
For example, the data in articles 2, 3 and 4 of the table are as follows:
List books = DataSupport.limit(3).offset(1).find(Book.class);

It can also query by combining the five methods mentioned above.
List books = DataSupport.select("name","author")
.where("price>?","10")
.order("pricre desc")
.limit(3)
.offset(1)
.find(Book.class);

If the above API s are not satisfied, you can also use native SQL to query:
Cursor cursor = DateSupport.findBySQL("select * from Book where pages > ? and price < ?", "200", "10");

Example:
Appbuild.gradle file

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    testCompile 'junit:junit:4.12'
    compile 'org.litepal.android:core:1.6.0'
}

App src main assets litepal. XML file

<?xml version="1.0" encoding="utf-8" ?>
<litepal>
    <dbname value="BookStore"></dbname>
    <version value="1"></version>
    <list>
        <mapping class="com.sky.litepaldemo.Book"></mapping>
    </list>
</litepal>

App src main Android Manifest. XML file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sky.litepaldemo">

    <application
        android:name="org.litepal.LitePalApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Model class Book.java

public class Book extends DataSupport {
    private int id;
    private String author;
    private double price;
    private int pages;
    private String bookName;

    public void setId(int id) {
        this.id = id;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public int getPages() {
        return pages;
    }

    public String getBookName() {
        return bookName;
    }

    public double getPrice() {
        return price;
    }

    public int getId() {
        return id;
    }

    public String getAuthor() {
        return author;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnCreateDatabase = (Button)findViewById(R.id.btnCreateDatabase);
        Button btnAddData = (Button)findViewById(R.id.btnAddData);
        Button btnUpdateData = (Button)findViewById(R.id.btnUpdateData);
        Button btnDeleteData = (Button)findViewById(R.id.btnDeleteData);
        Button btnQueryData = (Button)findViewById(R.id.btnQueryData);

        btnQueryData.setOnClickListener(this);
        btnDeleteData.setOnClickListener(this);
        btnUpdateData.setOnClickListener(this);
        btnAddData.setOnClickListener(this);
        btnCreateDatabase.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnCreateDatabase:
                Connector.getDatabase();
                Toast.makeText(this, "Create Database", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btnAddData:
                addData();
                Toast.makeText(this, "add data", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btnUpdateData:
                updateData();
                Toast.makeText(this, "update data", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btnDeleteData:
                deleteData();
                Toast.makeText(this, "delete data", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btnQueryData:
                queryData();
                Toast.makeText(this, "query data", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    private void queryData() {
        List<Book> bookList = DataSupport.findAll(Book.class);
        for (Book book:bookList){
            Log.d("MainActivity", "book name is:"+book.getBookName());
            Log.d("MainActivity", "book author is:"+book.getAuthor());
            Log.d("MainActivity", "book price is:"+book.getPrice());
            Log.d("MainActivity", "book pages is:"+book.getPages());
            Log.d("MainActivity", "------------------------------------------");
        }
    }

    private void deleteData() {
        DataSupport.deleteAll(Book.class, "price < ?", "30");
    }

    private void updateData() {
        Book books = new Book();
        books.setPrice(42.0);
        books.updateAll("author=?", "sky");
    }

    private void addData() {
        Book books = new Book();
        books.setBookName("adb");
        books.setAuthor("sky");
        books.setPages(600);
        books.setPrice(23.8);
        books.save();
        Book book2 = new Book();
        book2.setBookName("adb");
        book2.setAuthor("demo");
        book2.setPages(800);
        book2.setPrice(22.8);
        book2.save();
    }
}

Keywords: Android xml Database Junit

Added by tablex on Mon, 03 Jun 2019 23:27:47 +0300