Android——LitePal

1.配置LitePal环境

在project模式下,于build.gradle中dependencies段添加代码引用开源库:

compile 'org.litepal.android:core:1.4.1'

2.创建数据库

修改activity_main.xml文件:




    

在MainActivity文件添加代码:

Button createDatabase = (Button)findViewById(R.id.create_database);
createDatabase.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        LitePal.getDatabase();
    }
});

3.建立数据表

定义一个类:Book

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

    public int getId() {
        return id;
    }

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

    public String getAuthor() {
        return author;
    }

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

    public double getPrice() {
        return price;
    }

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

    public int getPages() {
        return pages;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPress() {
        return press;
    }

    public void setPress(String press) {
        this.press = press;
    }
}

添加到映射模型列表


        

4.添加数据

在MainActivity文件中添加代码:

//6.5.4添加数据
Button addData = (Button)findViewById(R.id.add_data);
addData.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Book book = new Book();
        book.setName("美人何处");
        book.setAuthor("安意如");
        book.setPages(330);
        book.setPrice(31);
        book.setPress("Unknow");
        book.save();
    }
});

参考博客:https://blog.csdn.net/qq_44852112/article/details/106103380

你可能感兴趣的:(Android)