gpt4 book ai didi

java - 为什么我的 Android 应用程序在插入行时崩溃?

转载 作者:行者123 更新时间:2023-11-29 22:30:27 26 4
gpt4 key购买 nike

我刚刚开始进行 Android 开发,但遇到了一些我的教科书无法帮助我解决的问题。

这是我的插入函数: 公共(public)长 insertEntry(BudgetsItem 项目){ 断言 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) 添加一个 if(db != null)

如果您的崩溃日志中的最后一行有效地在 db.insert 上。

如果有更多行,请将您的堆栈添加到您的帖子中,以便我们提供帮助

关于java - 为什么我的 Android 应用程序在插入行时崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4242073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com