Android LitePal的简单使用

为了丰富这个对于Android SQLite的使用,特别写了这篇文章,也算是做一个笔记吧。

效果图

在这里插入图片描述

正文


LitePal是Android中比较轻便的开源数据库框架,是郭霖大神写的,本文只做最简单的使用。

① 创建项目

在这里插入图片描述

然后是导入一些依赖库,其中包括LitePal,还有一些是为了方便展示数据的。

② 配置项目

在app下的build.gradle中添加配置

compileOptions {//指定使用的JDK1.8

sourceCompatibility = 1.8

targetCompatibility = 1.8

}

dataBinding {

enabled = true

}

//数据解析

implementation ‘com.squareup.retrofit2:converter-gson:2.4.0’

//Android SQLite操作框架

implementation ‘org.litepal.guolindev:core:3.1.1’

在这里插入图片描述

然后创建assets文件夹,文件夹下面新建一个litepal.xml文件

<?xml version="1.0" encoding="utf-8"?>

在这里插入图片描述

创建DemoApplication

在这里插入图片描述

然后在AndroidManifest.xml中指定

在这里插入图片描述

现在可以创建数据模型了。

③ 数据配置

在这里插入图片描述

这里建了一个model然后里面放数据实体,继承LitePalSupport是为了能够使用增删改查,代码如下:

package com.llw.litepalusedemo.model;

import org.litepal.crud.LitePalSupport;

//区/县

public class Area extends LitePalSupport {

private int id;//这个id是可以不用的,因为会默认创建一个自增的id

private String name;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

然后在litepal.xml中配置

在这里插入图片描述

④ 一顿操作

首先改动activity_main.xml布局,在最外侧增加标签,改动后代码如下:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:app=“http://schemas.android.com/apk/res-auto”

xmlns:tools=“http://schemas.android.com/tools”

android:layout_width=“match_parent”

android:orientation=“vertical”

android:layout_height=“match_parent”

tools:context=“.MainActivity”>

<TextView

android:id=“@+id/tv_result”

android:gravity=“center”

android:text=“结果”

android:textColor=“#000”

android:layout_width=“match_parent”

android:layout_height=“0dp”

android:layout_weight=“1”/>

<LinearLayout

android:gravity=“center”

android:orientation=“vertical”

android:layout_width=“match_parent”

android:layout_height=“0dp”

android:layout_weight=“1”>

<Button

android:id=“@+id/btn_add”

android:text=“增加数据”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”/>

<Button

android:id=“@+id/btn_update”

android:text=“修改数据”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”/>

<Button

android:id=“@+id/btn_query”

android:text=“查询数据”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”/>

<Button

android:id=“@+id/btn_delete”

android:text=“删除数据”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”/>

然后进入MainActivity,

代码如下:

package com.llw.litepalusedemo;

import androidx.appcompat.app.AppCompat
Activity;

import androidx.databinding.DataBindingUtil;

import android.os.Bundle;

import android.widget.Toast;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值