2017-07-31 78 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; 
      } 
     }; 
相關問題