已更新
我正在尝试创建一个DBHelper类并复制旧代码中的所有内容。但是,我似乎无法插入此内容。我不知道原因,我试图重新观看数据库中的教程,但我没有看到我的代码有任何错误。你能查一下这段代码吗?
DBHelper.Java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "DBName.db";
public static final String TABLE_NAME = "tblSample";
public static final String COL_1 = "ID";
public static final String COL_2= "Title";
public static final String COL_3 = "Content";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table IF NOT EXISTS " + TABLE_NAME + " " +
"(id integer primary key autoincrement, Title text, Content text) ");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertValue (String title, String cnt) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, title);
contentValues.put(COL_3, cnt);
long result = db.insert(TABLE_NAME, null, contentValues);
return result != -1;
//note this code is returning false
}
public Cursor selectSample(){
//I also tried to use this.getReadableDatabase();
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery( "select * from " + TABLE_NAME, null );
return res;
//this is returning 0 count
}
}
这是我在MainActivity.java
mydb = new DBHelper(this);
boolean hasError = mydb.insertValue("Title1", "content1");
if(!hasError){
Toast.makeText(getApplicationContext(), "No Error:",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Not Inserted:",Toast.LENGTH_LONG).show();
}
此代码显示Not Inserted:
含义,我无法插入db
您能否告诉我原因或至少告诉我如何在插入数据时显示错误消息。这样我至少可以意识到错误