2010-11-22 80 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。你确定你正在初始化它们吗?

相关问题