我正在尝试执行 SQLite 数据库示例,因为该表已成功创建但未插入值。请帮我。
public class MainActivity extends Activity {
String TAG = "MainActivity";
public DatabaseHelperAdapter dbHelper;
protected static final String String = null;
private Button save, cancel;
EditText fname, lname;
public static String FirstName = "";
public static String LastName = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save = (Button) findViewById(R.id.btn_save);
cancel = (Button) findViewById(R.id.btn_cancel);
fname = (EditText) findViewById(R.id.edit_fname);
lname = (EditText) findViewById(R.id.edit_lname);
dbHelper = new DatabaseHelperAdapter(MainActivity.this);
dbHelper.open();
save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dbHelper.addValues(FirstName, LastName);
}
});
}
数据库助手适配器
public class DatabaseHelperAdapter {
private static final String TAG = "DatabaseHelper";
public static final String Id = "_id";
public static final String FIRSTNAME = "first_name";
public static final String LASTNAME = "last_name";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private Context contex;
private static final String DATABASE_NAME = "Aadhaar";
private static final String DATABASE_TABLE = "Enrollment";
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE = "create table Enrollment (_id integer primary key autoincrement, "
+ "first_name text not null, last_name text not null);";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Regist");
onCreate(db);
}
}
public DatabaseHelperAdapter(Context contex) {
super();
this.contex = contex;
}
public DatabaseHelperAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(contex);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public long addValues(String fname, String lname) {
ContentValues initialValues = new ContentValues();
initialValues.put(FIRSTNAME, fname);
initialValues.put(LASTNAME, lname);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public void close() {
mDbHelper.close();
}
}
如果我通过 SQLite 编辑器手动输入值,那么值就会成功添加。