你们知道这段代码有什么问题吗?当我单击按钮将数据插入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();
}
}
这是Error异常所说的
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 Helper
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);
}
当应用程序尝试使用具有null值的对象引用时,将引发NullPointerException。
试试这个,
try {
SQLiteDatabase db = mSQLiteHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
Model modelOBJ = new Model();
cv.put("name", modelOBJ.setName(your_name_textOBJ.getText().toString());
cv.put("address", modelOBJ.setAddress(your_address_textOBJ.getText().toString());
cv.put("phone",modelOBJ.setPhone(your_phone_textOBJ.getText().toString());
db.insert("Table1", null, cv);
db.close();
}
catch (Exception e)
{
e.printStackTrace();
}
你在null对象引用上得到'Model.getName()'可能是你没有初始化你的模型类。做这个 :
YourModelClassName txn= new YourModelClassName (); // initialize your model class first
txn.setName(youNameEditext.getText().toString()); // set entered name in model class
public void onClick(View v) {
try {
SQLiteDatabase db = mSQLiteHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", txn.getName()); // get the entered name here.
cv.put("address", txn.getAddress());
cv.put("phone", txn.getPhone());
db.insert("Table1", null, cv);
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}