2012-04-27 33 views
0
public void execSqlFromAssets(String path) { 
    InputStream input; 
    String text; 
    try { 
     input = mCtx.getAssets().open(path + ".txt"); 
     int size = input.available(); 
     byte[] buffer = new byte[size]; 
     input.read(buffer); 
     input.close(); 
     text = new String(buffer); 
     String[] inserts = text.split(";"); 
     // SQLiteDatabase db = mDb; 
     for (String insert : inserts) { 
      insert = insert; 
      Log.w(TAG, insert); 
      try { 
       mDb.execSQL(insert); 
      } catch (Exception e) { 
       String err = (e.getMessage() == null) ? "Cant execute sql" 
         + insert : e.getMessage(); 
       Log.w(TAG, err); 
      } 
     } 

    } catch (IOException e) { 
     Log.w(TAG, "execSqlFromAssets: " + path + " file not found"); 
    } 

} 

這是我的代碼的問題是上線包含mDb.execSQL(插入)運行SQL語句。它會拋出異常,我無法讀取值爲空。我只是沒有得到它的錯誤信息之一是: 不能執行sqlINSERT INTO食物(名稱,cals)VALUES(「kolac」,270)。 任何幫助表示讚賞execSQL慣於從資產

+0

已解決......... – 2012-04-27 21:48:24

+0

請張貼解決方案作爲其他人的答案。 – 2012-04-27 22:19:19

回答

0

好,因爲@Preet Sangha要求我會發布解決方案。 我的問題是,我調用此函數在SQLiteOpenHelper比如在onCreate方法和 MDB實例wasnt尚未建立,所以我改變了功能,這

public void execSqlFromAssets(String path, SQLiteDatabase db) { 
    if(db == null){ 
     db = mDb; 
    } 
    InputStream input; 
    String text; 
    try { 
     input = mCtx.getAssets().open(path + ".txt"); 
     int size = input.available(); 
     byte[] buffer = new byte[size]; 
     input.read(buffer); 
     input.close(); 
     text = new String(buffer); 
     String[] inserts = text.split(";"); 
     for (String insert : inserts) { 
      try { 
       db.execSQL(insert); 
      } catch (Exception e) { 
       String err = (e.getMessage() == null) ? "Cant execute sql" 
         + insert : e.getMessage(); 
       Log.w(TAG, err); 
      } 
     } 

    } catch (IOException e) { 
     Log.w(TAG, "execSqlFromAssets: " + path + " file not found"); 
    } 

} 

所以現在如果我打電話從的onCreate這個功能我會發送DB作爲第二個參數,如果我從另一個應用程序組件調用它,我會發送null作爲第二個參數

+0

如果你想我可以複製整個班級 – 2012-04-28 09:49:01