在 logcat 我有这个错误:
12-05 19:20:26.696: E/SQLiteDatabase(1415): Error inserting lon=5.25 lat=7.52 name=null
12-05 19:20:26.696: E/SQLiteDatabase(1415): android.database.sqlite.SQLiteException: no such table: position (code 1): , while compiling: INSERT INTO position(lon,lat,name) VALUES (?,?,?)
我尝试在名为:位置的表中插入 3 个值:名称、纬度、经度。在代码中我没有任何错误并且应用程序不会崩溃。我已将插入值的事件附加到带有 onClickListener 的按钮(当用户按下按钮时,插入值)。
创建数据库的代码:
公共类 listagpsdb {
SQLiteDatabase mDb; DbHelper mDbHelper; Context mContext; private static final String DB_NAME="listagps"; private static final int DB_VERSION=1; public listagpsdb(Context ctx){ mContext=ctx; mDbHelper=new DbHelper(ctx, DB_NAME, null, DB_VERSION); } public void open(){ //il database su cui agiamo è leggibile/scrivibile mDb=mDbHelper.getWritableDatabase(); } public void close(){ mDb.close(); } public void insertPosition(String name,double lat, double lon){ ContentValues cv=new ContentValues(); cv.put(PositionsMetaData.POSITIONS_NAME_KEY, name); cv.put(PositionsMetaData.POSITIONS_LATITUDE_KEY, lat); cv.put(PositionsMetaData.POSITIONS_LONGITUDE_KEY, lon); mDb.insert(PositionsMetaData.POSITIONS_TABLE, null, cv); } public Cursor fetchProducts(){ return mDb.query(PositionsMetaData.POSITIONS_TABLE, null,null,null,null,null,null); } static class PositionsMetaData { static final String POSITIONS_TABLE = "position"; static final String ID = "_id"; static final String POSITIONS_NAME_KEY = "name"; static final String POSITIONS_LATITUDE_KEY = "lat"; static final String POSITIONS_LONGITUDE_KEY = "lon"; } private static final String POSITIONS_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS" + PositionsMetaData.POSITIONS_TABLE + " (" + PositionsMetaData.ID+ " integer primary key autoincrement, " + PositionsMetaData.POSITIONS_NAME_KEY + " text, " + PositionsMetaData.POSITIONS_LATITUDE_KEY + " double not null);" + PositionsMetaData.POSITIONS_LONGITUDE_KEY + "double not null);"; private class DbHelper extends SQLiteOpenHelper { public DbHelper(Context context, String name, CursorFactory factory,int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase _db) { _db.execSQL(POSITIONS_TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) { } }
}
在您看到的代码中,我只想在创建数据库时创建表。
这是活动类的代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navi);
Button SalvaLocation = (Button) findViewById(R.id.SalvaLocation);
final listagpsdb db = new listagpsdb(getApplicationContext());
SalvaLocation.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
db.open();
String name = null;
Double lat = 7.52;
Double lon = 5.25;
db.insertPosition(name, lat, lon);
db.close();
}
});
现在我不明白为什么没有创建数据库/表。有人有想法吗? 如果创建了数据库,在 AVD 内存中可以看到一个技巧?
感谢所有想帮助我的人!