我们知道Android中有四种数据存储方式:
SharedPreference存储
content provider
SQLite数据库存储
文件存储
今天我们主要说 本地数据库sqlite这种方式,实现读取一个本地数据库db文件的功能。为了方便说明,我举个例子来讲:
我们创建一个本地数据库,里面包含两张表 一个用户表user 一个性别表 gender
要求:1.将用户表中用户查询出来,性别需要显示男女,用listView展示出来。
2.修改 将用户表中 王杰修改为李四
3.增加长按删除功能
非常简单的功能,那么我们实现这个需要做以下几步操作。
1.将本地数据库db文件拷贝到项目中
2.将项目中db文件写入到本地文件夹中
3.增加打开数据库以及数据读取逻辑
4.增加删除逻辑 ,增加修改逻辑。
需要注意的有几点:
1)拷贝数据库涉及到读写 ,所以权限这块需要注意,如果是22以上的需要申请权限,否则会报错。
2)assets文件夹是在main文件夹下面建和res是平级,之前很多来面试的还把文件夹都放错了。
3)读取用户时候,性别一栏是需要做关联查询的 ,因为用户表性别用的是字典值。
Android拷贝逻辑代码
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 本地 操作数据库逻辑(查,删,改)
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<User> queryUser() { List<User> userList = new ArrayList<User>(); 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}); } }