【发布时间】:2019-02-10 03:10:20
【问题描述】:
你们知道这段代码有什么问题吗?当我单击按钮将数据插入 sqlite 外部数据库时。但它似乎不起作用。错误显示在cv.put("name", txn.getName()); 也许是我写错了?
Java 页面
public void onClick(View v) {
try {
SQLiteDatabase db = mSQLiteHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", txn.getName());
cv.put("address", txn.getAddress());
cv.put("phone", txn.getPhone());
db.insert("Table1", null, cv);
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
这里是错误异常说
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.waiku.work2.Model.getName()' on a null object reference
这是我的 OOP 模型,我有点困惑它是如何工作的。但我遵循了 youtube 教程...
public class Model {
private int id;
private String name;
private String address;
private int phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
}
这是我的 SQLite 助手
public class SQLiteHelper extends SQLiteAssetHelper {
private static final String DB_NAME = "MyExternalDatabase.db";
private static final int DATABASE_VERSION = 1;
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
}
【问题讨论】:
-
txn 为空。你从哪里得到那个模型类?
-
在java页面。我输入了
public static Model txn;所以它是模型。内部模型有“名称”“地址”和“电话”。 @sunilsunny
标签: android sqlite oop android-sqlite