因此,每次我将数据输入到位于我的AddContacts类中的EditText字段时,我的Dialog说我已经成功添加了信息,但是在日志中它没有说明这样的表: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;
}
}
答案 0 :(得分:3)
您在运行应用程序至少一次后更改了DATABASE_TABLE
了吗?如果是这样,您需要更新SQLite架构,最简单的方法是make DATABASE_VERSION = 2;
。 Android也非常关注主键,您应该将COL_ID
更改为"_id"
。
将来,每次更改DATABASE_VERSION
声明时都必须增加CREATE_TABLE
。否则SQLite将没有当前信息。