2010-11-22 43 views
1

我剛剛開始使用android開發,而且我遇到了一些問題,我的教科書並未幫助我。爲什麼我的Android應用在行插入時崩潰?

這是我的插入函數: public long insertEntry(BudgetsItem item){ assert item.id == -1;

ContentValues newBudgetValues = new ContentValues(); 
    newBudgetValues.put("name", item.name); 
    newBudgetValues.put("balance", item.balance); 

    item.id = db.insert(DATABASE_TABLE_NAME, null, newBudgetValues); 

    return item.id; 
} 

這是我的表定義:

private static final String TABLE_CREATE = "CREATE " + DATABASE_TABLE_NAME + "(\n" + 
    "id INTEGER PRIMARY KEY AUTOINCREMENT, \n" + 
    "name TEXT, \n" + 
    "balance DOUBLE);"; 

而這就是在調用適配器崩潰之前:

 BudgetsAdapter adapter = new BudgetsAdapter(getBaseContext()); 
     BudgetsItem newBudget = new BudgetsItem(budgetName, balance); 
     if(adapter.insertEntry(newBudget) != -1){ 
      Toast.makeText(getApplicationContext(), "Budget Created!", Toast.LENGTH_SHORT); 
      finish(); 
     }else{ 
      Toast.makeText(getApplicationContext(), "Oops, something failed.", Toast.LENGTH_SHORT); 
     } 

它崩潰的db.insert符合一個NullPointerException 。誰能告訴我爲什麼?

回答

1

你沒有給我們任何資料,你db對象(我猜表示數據庫。

,因爲你說崩潰就分貝插入我不得不猜測,DB是此刻不初始化您做一個插入 我建議 1)如果崩潰日誌中的最後一行在db.insert上有效,則添加一個if(db!= null)

,如果有更多的線路,請你的籌碼添加到您的文章,所以我們可以幫助

+0

你說得對,調用adapter.open時分配db,我忘了調用它。 – Malfist 2010-11-22 03:58:38

1

在這種情況下,有一件事是可以爲空:db。你確定你正在初始化它們嗎?

相關問題