Zam*_*FTW 0 java sqlite android android-sqlite
我正在制作一个小应用程序,以读取一些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());
}
}
Run Code Online (Sandbox Code Playgroud)
如果您要在db中执行多项操作,最好是在其他线程中运行,并尝试使用事务,
尝试这个,
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;
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
541 次 |
最近记录: |