2015-04-03 49 views
0

我在我的android應用程序上執行數據庫,並且我想使用從csv派生的值對它進行初始化。 這裏是我的代碼:使用csv進行Android數據庫初始化

@Override 
public void onCreate(SQLiteDatabase database) { 
    executeSQLScript(database, "bdd.sql"); 
    addComercialCsv(database,"commerciaux.csv"); 
} 

public void addComercialCsv(SQLiteDatabase database, String filename){ 
    int id,code = 0,idAdress= 0, cp= 0, nom= 0, tel= 0, mail= 0, cplt1= 0, cplt2= 0, rue= 0, localite= 0, ville= 0, pays= 0; 
    String insertAdresse = "INSERT INTO Adresse (cplt1,cplt2,rue,localite,cp,ville,pays) values("; 
    String insertComm = "INSERT INTO Commercial (code,nom,prenom,tel,mail,adresse) values ("; 
    String close = ");"; 
    String prenom = "", noms = ""; 
    AssetManager assetManager = context.getAssets(); 

    InputStreamReader is = null; 
    try { 
     is = new InputStreamReader(assetManager.open(filename)); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    BufferedReader reader = new BufferedReader(is); 
    String line = null; 
    try { 
     line = reader.readLine(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    String[] header = line.split(";"); 

    int cpt = 0; 
    for(String name : header){ 

     if (name.equals("Commercial")){ 
      code = cpt; 
     }else if (name.equals("Nom")){ 
      nom = cpt; 
     }else if (name.equals("Code postal")){ 
      cp = cpt; 
     }else if (name.equals("Ville")){ 
      ville = cpt; 
     }else if (name.equals("Adresse complement 1")){ 
      cplt1 = cpt; 
     }else if (name.equals("Adresse complement 2")){ 
      cplt2 = cpt; 
     }else if (name.equals("Rue")){ 
      rue = cpt; 
     }else if (name.equals("Localite")){ 
      localite = cpt; 
     }else if (name.equals("Telephone")){ 
      tel = cpt; 
     }else if (name.equals("Mail")){ 
      mail = cpt; 
     }else if (name.equals("Pays")){ 
      pays = cpt; 
     } 
     cpt += 1; 
    } 
    database.beginTransaction(); 
    try { 
     while ((line = reader.readLine()) != null) { 

      StringBuilder insertAdres = new StringBuilder(insertAdresse); 
      String[] str = line.split(";"); 
      insertAdres.append("'"+str[cplt1]+"',"); 

      insertAdres.append("'"+str[cplt2]+"',"); 
      insertAdres.append("'"+str[rue]+"',"); 
      insertAdres.append("'"+str[localite]+"',"); 
      insertAdres.append("'"+str[cp]+"',"); 
      insertAdres.append("'"+str[ville]+"',"); 
      insertAdres.append("'"+str[pays]+"'"); 
      insertAdres.append(close); 

      System.out.println(insertAdres); 
      database.execSQL(insertAdres.toString()); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    database.endTransaction(); 
} 

的問題是,我的數據庫沒有創建它,當我執行我的功能「addCommercialCsv」當我不使用此功能創建我的數據庫。

是什麼問題?

回答

0

你開始交易與beginTransaction()但從來沒有把它設置爲成功的setTransactionSuccessful()。沒有它endTransaction()回滾更改,而不是提交它們。

另請注意,onCreate(SQLiteDatabase)已在事務中運行,並且您不應啓動嵌套事務,並將數據庫作爲參數傳入onCreate()