因此,每次我在位于 AddContacts 类中的 EditText 字段中输入数据时,我的对话框都会说我已经成功添加了信息,但是在日志 cat 中它说没有这样的表:contactsTable。我认为错误在我的数据库类中的 onCreate 和 onUpdate 方法中,但我不知道该怎么做
代码:
package com.example.myfirstapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseTable {
private static final String TAG = "ContactsDatabase";
//The columns we'll include in the contacts table
public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_EMAIL = "EMAIL";
private static final String DATABASE_NAME = "CONTACT";
private static final String DATABASE_TABLE = "contactsTable";
private static final int DATABASE_VERSION = 1;
private Context ourContext;
private DbHelper DBHelper;
private SQLiteDatabase db;
private static final String DATABASE_CREATE =
"CREATE TABLE " + DATABASE_TABLE + " (" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT NOT NULL, " +
COL_EMAIL + " TEXT NOT NULL);";
private static class DbHelper extends SQLiteOpenHelper {
DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public DatabaseTable(Context context) {
ourContext = context;
}
public DatabaseTable open() throws SQLException {
DBHelper = new DbHelper(ourContext);
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public long insertContact(String name, String email) {
ContentValues initialValues = new ContentValues();
initialValues.put(COL_NAME, name);
initialValues.put(COL_EMAIL, email);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public void deleteRecord(long rowId)
{
db.delete(DATABASE_TABLE, COL_ID + "=" + rowId, null);
}
public Cursor getAllRecords() {
return db.query(DATABASE_TABLE, new String[] {COL_ID, COL_NAME, COL_EMAIL}, null,
null, null, null, null);
}
public Cursor getRecord(long rowId) throws SQLException {
Cursor cursor = db.query(true, DATABASE_TABLE, new String[] {COL_ID, COL_NAME,
COL_EMAIL}, COL_ID + "=" + rowId, null, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
return cursor;
}
public boolean updateRecord(long rowId, String name, String email) {
ContentValues content = new ContentValues();
content.put(COL_NAME, name);
content.put(COL_EMAIL, email);
return db.update(DATABASE_TABLE, content, COL_ID + "=" + rowId, null) > 0;
}
}