Reputation: 105
I am trying to insert lat and long coordinates into a SQLite table and I am getting SQLiteConstraintException: error code 19: constraint failed
.
I have the code surrounded by try/catch and no exception is thrown. I get the constraint error in my logcat.
I have attached the DB class and the call from my main activity. Any help or guidance would be very much appreciated!
Here are the top few lines from my logcat:
08-25 14:39:06.934: E/SQLiteDatabase(681): Error inserting lat=59310767 longi=-8613281
08-25 14:39:06.934: E/SQLiteDatabase(681): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
08-25 14:39:06.934: E/SQLiteDatabase(681): at android.database.sqlite.SQLiteStatement.native_executeInsert(Native Method)
08-25 14:39:06.934: E/SQLiteDatabase(681): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:113)
08-25 14:39:06.934: E/SQLiteDatabase(681): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1745)
08-25 14:39:06.934: E/SQLiteDatabase(681): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1618)
Here is the code from my DbHelper:
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_LAT + " REAL NOT NULL, " +
KEY_LONGI + " REAL NOT NULL)"
// KEY_NAME + " TEXT NULL, " +
// KEY_INFO + " TEXT NULL);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
Here is my DatabaseManager
public DatabaseManager(Context c) {
ourContext = c;
}
public DatabaseManager open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDB = ourHelper.getWritableDatabase(); //example show writeable
return this;
}
public void close() {
ourHelper.close();
}
public long createPin(long latitude, long longitude) {
ContentValues cv = new ContentValues();
cv.put(KEY_LAT, latitude);
cv.put(KEY_LONGI, longitude);
return ourDB.insert(DATABASE_TABLE, null, cv);
}
This is the call from my MainActivity:
try{
long longitude= touchedPoint.getLongitudeE6();
long latitude= touchedPoint.getLatitudeE6();
//Add Pin to the Database
DatabaseManager db = new DatabaseManager(MainActivity.this);
db.open();
db.createPin(latitude,longitude);
db.close();
}
Upvotes: 2
Views: 4952
Reputation: 12523
remove the keyword AUTOINCREMENT. It is not necessaty for sqlite. if you try to insert a null value into a primary integer key the field is automatically converted into an integer which is one greater than the largest value of that column.
Furthermore you have to clear your appdata on your emulator. After that you can be sure that the database is empty.
Upvotes: 2