android 读取本地数据库db文件(Android sqlite)

android 读取本地数据库db文件(Android sqlite)

大家好,又见面了,我是你们的朋友全栈君。

我们知道Android中有四种数据存储方式:

SharedPreference存储content providerSQLite数据库存储文件存储今天我们主要说 本地数据库sqlite这种方式,实现读取一个本地数据库db文件的功能。为了方便说明,我举个例子来讲:

我们创建一个本地数据库,里面包含两张表 一个用户表user 一个性别表 gender

要求:1.将用户表中用户查询出来,性别需要显示男女,用listView展示出来。

2.修改 将用户表中 王杰修改为李四

3.增加长按删除功能

非常简单的功能,那么我们实现这个需要做以下几步操作。

1.将本地数据库db文件拷贝到项目中

2.将项目中db文件写入到本地文件夹中

3.增加打开数据库以及数据读取逻辑

4.增加删除逻辑 ,增加修改逻辑。

需要注意的有几点:

1)拷贝数据库涉及到读写 ,所以权限这块需要注意,如果是22以上的需要申请权限,否则会报错。

2)assets文件夹是在main文件夹下面建和res是平级,之前很多来面试的还把文件夹都放错了。

3)读取用户时候,性别一栏是需要做关联查询的 ,因为用户表性别用的是字典值。

Android拷贝逻辑代码

代码语言:javascript复制package com.example.testdemo.util;

import android.content.Context;

import android.os.Environment;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

public class FileUtil {

private static String mWorkPath = null;

private static String mRootPath = null;

private static Boolean mGetSDpath = false;

private final static String DB_PATH_NAME = "database/";

public static long copyTime = 0;

private static Context mContext;

public static String getRootPath() {

if (!mGetSDpath || mRootPath == null) {

mGetSDpath = true;

boolean sdCardExist = Environment.getExternalStorageState().equals(

Environment.MEDIA_MOUNTED); // 判断sd卡是否存在

if (sdCardExist) {

File sdDir = Environment.getExternalStorageDirectory();// 获取跟目录

mRootPath = sdDir.toString();

} else {

mRootPath = mContext.getFilesDir().toString();

}

}

if (!mRootPath.endsWith("/"))

mRootPath += "/";

return mRootPath;

}

/**

* 设置工作目录

*

* @param context app context,不然会造成内存泄漏

* @param path

*/

public static void setWorkPath(Context context, String path) {

mContext = context;

if (null != getRootPath()) {

mWorkPath = mRootPath + path;

}

if (!mWorkPath.endsWith("/")) {

mWorkPath += "/";

}

File file = new File(mWorkPath);

if (!file.exists()){

boolean b = file.mkdirs();

}

}

public static String getDBpath() {

File file = new File(mWorkPath + DB_PATH_NAME);

if (!file.exists())

file.mkdirs();

return mWorkPath + DB_PATH_NAME;

}

public static void copyAccessDB(Context context) {

try {

String[] dbNames = context.getAssets().list("db");

for (String dbName : dbNames) {

long startTime = System.currentTimeMillis();

String filePath = FileUtil.getDBpath() + dbName;

File dbFile = new File(filePath);

if (!dbFile.exists()) {

FileOutputStream fos = null;

try {

dbFile.createNewFile();

}catch (Exception e){

}

InputStream is = context.getAssets().open("db/" + dbName);

fos = new FileOutputStream(dbFile);

byte[] buffer = new byte[2048];

int len = -1;

while ((len = is.read(buffer)) != -1) {

fos.write(buffer, 0, len);

}

fos.close();

long endTime = System.currentTimeMillis();

long useTime = endTime - startTime;

copyTime += useTime;

}

}

} catch (IOException e) {

e.printStackTrace();

}

}

}Android 本地 操作数据库逻辑(查,删,改)

代码语言:javascript复制package com.example.testdemo.util;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Environment;

import com.example.testdemo.bean.User;

import java.util.ArrayList;

import java.util.List;

public class DBManager {

private Context mContext;

private SQLiteDatabase mDB;

private static String dbPath = FileUtil.getDBpath() + "/Test.db";

private static DBManager instance = null;

public DBManager() {

}

public static DBManager getInstance() {

if (instance == null) {

instance = new DBManager();

}

return instance;

}

/**

* 打开数据库

*/

private void openDB() {

if (isSDCard()) {

if (mDB == null || !mDB.isOpen())

mDB = SQLiteDatabase.openDatabase(dbPath, null,

SQLiteDatabase.OPEN_READWRITE);

}

}

private boolean isSDCard() {

return Environment.getExternalStorageState().equals(

Environment.MEDIA_MOUNTED);

}

//查询选择题

public List queryUser() {

List userList = new ArrayList();

User user= null;

openDB();

try {

String sql = " select a.id,a.name,a.age,a.phoneNum,b.name as sexName from user a,gender b where a.sex= b.type";

Cursor cursor = mDB.rawQuery(sql, null);

while (cursor.moveToNext()) {

String id = cursor.getString(cursor.getColumnIndex("id"));

String name = cursor.getString(cursor.getColumnIndex("name"));

String sex = cursor.getString(cursor.getColumnIndex("sexName"));

String age = cursor.getString(cursor.getColumnIndex("age"));

String phoneNum = cursor.getString(cursor.getColumnIndex("phoneNum"));

user= new User();

user.setId(id);

user.setName(name);

user.setAge(age);

user.setPhoneNum(phoneNum);

user.setSex(sex);

userList.add(user);

}

cursor.close();

return userList;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

public void updateUser() {

openDB();

String sql = " update user set name = '李四' where name = '王杰' ";

mDB.execSQL(sql);

}

public void deleteUser(String id) {

openDB();

mDB.delete("user", " id = ? ", new String[]{id});

}

}基本最核心的就这些代码,不是很复杂,贴上效果图。

我知道有的小伙伴需要完整的DEMO,所以我就整理了一个 ,在这里DEMO下载。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/138369.html原文链接:https://javaforall.cn

相关推荐

真我realme手机AI美颜有哪些效果?
365登录次数限制

真我realme手机AI美颜有哪些效果?

📅 07-16 👁️ 7733
伽利略生平简介,伽利略历史评价,伽利略怎么死的?
365现在还能安全提款吗

伽利略生平简介,伽利略历史评价,伽利略怎么死的?

📅 10-13 👁️ 3270
深圳入职体检一般要多少钱
365登录次数限制

深圳入职体检一般要多少钱

📅 08-13 👁️ 2963
如何下载车牌号和番号资源?
365bet直播

如何下载车牌号和番号资源?

📅 10-22 👁️ 9854
美团最近常买记录怎么删除 美团最近常买怎么删除
365现在还能安全提款吗

美团最近常买记录怎么删除 美团最近常买怎么删除

📅 07-21 👁️ 3716
全新铲车
365现在还能安全提款吗

全新铲车

📅 10-07 👁️ 2376
AI编程神器:Claude Code安装与国内免费使用(保姆级教程)
365现在还能安全提款吗

AI编程神器:Claude Code安装与国内免费使用(保姆级教程)

📅 07-30 👁️ 8603
联想 p780 手机怎么样?续航及性能评测
365bet直播

联想 p780 手机怎么样?续航及性能评测

📅 10-14 👁️ 3469
三国志10截图壁纸
365登录次数限制

三国志10截图壁纸

📅 09-23 👁️ 663