2017-07-31 26 views
0

我正在制作一个小应用程序来读取一些txt文件并将其导入设备上的SQLite数据库。
问题是,当我正确读取和导入文件时,应用程序在执行该方法时冻结。我想展示一个进度条或类似的东西,但是这个问题我无能为力。
这是进口方法代码:
插入时冻结应用程序(Android 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()); 
    } 
} 
+0

当你的应用程序冻结时,你应该在你的日志猫中看到一个错误日志。你可以补充说 –

+0

事情是,它不会给我错误。只有“跳过1106帧!应用程序可能在其主线程上做了太多工作。” – ZamoraFTW

+0

然后就像它说的那样,你在主线程中做了太多的操作,所以你需要在后台线程中执行它。你的txt文件有多大 –

回答

4

你,如果你正在做的分贝多种业务,更好的是你应该在不同的线程中运行,并且还试图使用事务,

试试这个,

 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; 
      } 
     }; 
相关问题