我正在制作一个小应用程序来读取一些 txt 文件并将其导入到设备上的 SQLite 数据库中。
问题是,当我正确读取和导入文件时,应用程序在执行该方法时卡住。我想显示一个进度条或类似的东西,但对于这个问题我无能为力。
这是导入方法代码:
private void importFilesFromTxt() {
bd = helper.getWritableDatabase();
File directorio = getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS);
File file = new File(directorio, "art01.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
String[] parts;
String sql = "delete from Articulos";
bd.execSQL(sql);
while ((line = br.readLine()) != null) {
if (line.length() != 328) {
parts = line.split("\\#+");
Articulo arti = new Articulo(Integer.parseInt(parts[0]), parts[1], quitarEspaciosInt(parts[2]), quitarEspaciosInt(parts[3])
, convertirDecimal(parts[4]), quitarEspaciosInt(parts[5]), quitarEspaciosInt(parts[6]), quitarEspaciosFloat(parts[7]), quitarEspaciosInt(parts[8]));
helper.addArticulo(arti);
}
}
bd.close();
br.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
最佳答案
如果您对数据库进行多个操作,更好的是您应该在不同的线程中运行并尝试使用事务,
试试这个,
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
bd = helper.getWritableDatabase();
File directorio = getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS);
File file = new File(directorio, "art01.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
String[] parts;
String sql = "delete from Articulos";
bd.execSQL(sql);
bd.beginTransaction();
while ((line = br.readLine()) != null) {
if (line.length() != 328) {
parts = line.split("\\#+");
Articulo arti = new Articulo(Integer.parseInt(parts[0]), parts[1], quitarEspaciosInt(parts[2]), quitarEspaciosInt(parts[3])
, convertirDecimal(parts[4]), quitarEspaciosInt(parts[5]), quitarEspaciosInt(parts[6]), quitarEspaciosFloat(parts[7]), quitarEspaciosInt(parts[8]));
helper.addArticulo(arti);
}
}
br.close();
bd.setTransactionSuccessful();
} catch (IOException e) {
// System.out.println(e.toString());
} catch (Exception e) {
} finally {
bd.endTransaction();
bd.close();
}
return null;
}
};
关于java - 插入时应用程序卡住(Android SQLite DB),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411356/