示例图
现在要进行读取xcz1.db 中的 数据那么读取数据之前要知道表明字段名,如果知道直接绕过 1 看 导航2 .
1 在不知道的情况下我们可以使用工具 Navicat Premium 进行查看,示例图
这样我们就能看到表明和字段名等信息 那么我们知道了这些信息直接进行 将数据库复制本都 进行读取就OK ,直接上代码
2 进行读写权限申请
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
ArrayList<String> list=new ArrayList<>();
list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
list.add(Manifest.permission.READ_EXTERNAL_STORAGE);
for (int i = 0; i <list.size() ; i++) {
if (ContextCompat.checkSelfPermission(this,list.get(i))!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{list.get(i)}, MIME);
}
}
3 进行数据库读取和拷贝 上工具类
public class AssetsDBUtils {
//packagename 改成你的包名
public static final String packageBame = "com.example.jing.myapplication";
// 修改成你assets 中的 .db 文件的名字
public static final String db_name = "xcz1.db";
public static final String filePath = "data/data/" + packageBame + "/databases/" + db_name;
public static final String pathStr = "data/data/" + packageBame + "/databases";
public static String getPath(Context context) {
System.out.println("filePath:" + filePath);
File dbFile = new File(filePath);
if (dbFile.exists()) {
return filePath;
} else {
File path = new File(pathStr);
path.mkdir();
try {
InputStream is = context.getClass().getClassLoader().getResourceAsStream("assets/" + db_name);
FileOutputStream fos = new FileOutputStream(dbFile);
byte[] buffer = new byte[10240];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.flush();
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return filePath;
}
}
}
4 这样我们就能拿到 .db 文件的路径就行进行读取了
String path = AssetsDBUtils.getPath(this);
sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(path, null);
thread = new Thread(new Runnable() {
@Override
public void run() {
Cursor cs = sqLiteDatabase.query("authors", new String[]{"*"}, null, null, null, null, null);
while (cs.moveToNext()) {
//名字
String name = cs.getString(cs.getColumnIndex("name"));
//简介
String intro = cs.getString(cs.getColumnIndex("intro"));
//朝代
String dynasty = cs.getString(cs.getColumnIndex("dynasty"));
//出生时间
String birth_year = cs.getString(cs.getColumnIndex("birth_year"));
//死亡时间
String death_year = cs.getString(cs.getColumnIndex("death_year"));
//id 主键
long id = cs.getLong(cs.getColumnIndex("id"));
user_beanArrayList.add(new User_Bean(name,intro,dynasty,birth_year,death_year,id));
}
}
});
thread.start();
记得放到线程 中 读取数据库等都是耗时操作, 线程在Activity销毁的时候记得销毁线程, 因为在Acticity销毁的时候对象等可能会被跟着销毁但是线程不会。