Java 类android.database.sqlite.SQLiteConstraintException 实例源码
项目:YuiHatano
文件:ShadowDatabaseUtils.java
private static final void readExceptionFromParcel(Parcel reply, String msg, int code) {
switch (code) {
case 2:
throw new IllegalArgumentException(msg);
case 3:
throw new UnsupportedOperationException(msg);
case 4:
throw new SQLiteAbortException(msg);
case 5:
throw new SQLiteConstraintException(msg);
case 6:
throw new SQLiteDatabaseCorruptException(msg);
case 7:
throw new SQLiteFullException(msg);
case 8:
throw new SQLiteDiskIOException(msg);
case 9:
throw new SQLiteException(msg);
case 11:
throw new OperationCanceledException(msg);
default:
reply.readException(code, msg);
}
}
项目:inventum
文件:MovieProvider.java
@Nullable
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
MovieUriEnum matchingUriEnum = mUriMatcher.matchUri(uri);
if (matchingUriEnum.table != null) {
try {
db.insertOrThrow(matchingUriEnum.table, null, values);
} catch (SQLiteConstraintException e) {
throw e;
}
}
switch (matchingUriEnum) {
case MOVIES:
return Movies.buildMovieUri(values.getAsString(Movies.MOVIE_ID));
case TVS:
return TVs.buildTVUri(values.getAsString(TVs.TV_ID));
case PERSONS:
return Persons.buildPersonUri(values.getAsString(Persons.PERSON_ID));
default:
throw new UnsupportedOperationException("Unknown insert URI: " + uri);
}
}
项目:Remindy
文件:RemindyDAO.java
/**
* Returns a Task (with Reminder and Attachments) given a taskId
* @param taskId The ID of the Task to get.
*/
public Task getTask(int taskId) throws CouldNotGetDataException, SQLiteConstraintException {
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(RemindyContract.TaskTable.TABLE_NAME, null, RemindyContract.PlaceTable._ID + "=?",
new String[]{String.valueOf(taskId)}, null, null, null);
if (cursor.getCount() == 0)
throw new CouldNotGetDataException("Specified Task not found in the database. Passed id=" + taskId);
if (cursor.getCount() > 1)
throw new SQLiteConstraintException("Database UNIQUE constraint failure, more than one record found. Passed value=" + taskId);
cursor.moveToNext();
Task task = getTaskFromCursor(cursor);
task.setAttachments(getAttachmentsOfTask(taskId));
if(task.getReminderType() != ReminderType.NONE)
task.setReminder(getReminderOfTask(taskId, task.getReminderType()));
return task;
}
项目:ChatKeyboard-master
文件:EmoticonDBHelper.java
public synchronized long insertEmoticonBean(EmoticonBean bean, String beanSetName) {
SQLiteDatabase db = mOpenDbHelper.getWritableDatabase();
long result = -1;
if (bean == null || db == null) {
return result;
}
ContentValues values = new ContentValues();
values.put(TableColumns.EmoticonColumns.EVENT_TYPE, bean.getEventType());
values.put(TableColumns.EmoticonColumns.TAG, bean.getTag());
values.put(TableColumns.EmoticonColumns.NAME, bean.getName());
values.put(TableColumns.EmoticonColumns.ICON_URI, bean.getIconUri());
values.put(TableColumns.EmoticonColumns.MSG_URI, bean.getMsgUri());
values.put(TableColumns.EmoticonColumns.EMOTICON_SET_NAME, beanSetName);
try {
result = db.insert(TABLE_NAME_EMOTICONS, null, values);
} catch (SQLiteConstraintException e) {
Log.e(TAG, "insert failed", e);
}
return result;
}
项目:KBUnitTest
文件:ShadowDatabaseUtils.java
private static final void readExceptionFromParcel(Parcel reply, String msg, int code) {
switch (code) {
case 2:
throw new IllegalArgumentException(msg);
case 3:
throw new UnsupportedOperationException(msg);
case 4:
throw new SQLiteAbortException(msg);
case 5:
throw new SQLiteConstraintException(msg);
case 6:
throw new SQLiteDatabaseCorruptException(msg);
case 7:
throw new SQLiteFullException(msg);
case 8:
throw new SQLiteDiskIOException(msg);
case 9:
throw new SQLiteException(msg);
case 11:
throw new OperationCanceledException(msg);
default:
reply.readException(code, msg);
}
}
项目:Show_Chat
文件:MovieProvider.java
@Nullable
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
MovieUriEnum matchingUriEnum = mUriMatcher.matchUri(uri);
if (matchingUriEnum.table != null) {
try {
db.insertOrThrow(matchingUriEnum.table, null, values);
} catch (SQLiteConstraintException e) {
throw e;
}
}
switch (matchingUriEnum) {
case MOVIES:
return Movies.buildMovieUri(values.getAsString(Movies.MOVIE_ID));
case TVS:
return TVs.buildTVUri(values.getAsString(TVs.TV_ID));
case PERSONS:
return Persons.buildPersonUri(values.getAsString(Persons.PERSON_ID));
default:
throw new UnsupportedOperationException("Unknown insert URI: " + uri);
}
}
项目:GreenDAOCrud
文件:UserCRUD.java
public void addNewUser()
{
User person = new User();
person.setFirstname(getData(txtFirstname));
person.setAge(getData(txtAge));
person.setNic(getData(txtNIC));
person.setSurname(getData(txtSurname));
try {
long f = user.insert(person);
if (f > 0) {
showToast("User added");
clearAllTextData();
}
else
{
showToast("User not added");
}
}
catch (SQLiteConstraintException e)
{
showToast("User with the same NFC id Exists");
}
}
项目:core-doppl
文件:DatabaseStatementTest.java
@MediumTest
public void testStatementConstraint() throws Exception {
mDatabase.execSQL("CREATE TABLE test (num INTEGER NOT NULL);");
SQLiteStatement statement = mDatabase.compileStatement("INSERT INTO test (num) VALUES (?)");
// Try to insert NULL, which violates the constraint
try {
statement.clearBindings();
statement.execute();
fail("expected exception not thrown");
} catch (SQLiteConstraintException e) {
// expected
}
// Make sure the statement can still be used
statement.bindLong(1, 1);
statement.execute();
statement.close();
Cursor c = mDatabase.query("test", null, null, null, null, null, null);
int numCol = c.getColumnIndexOrThrow("num");
c.moveToFirst();
long num = c.getLong(numCol);
assertEquals(1, num);
c.close();
}
项目:sqlite-android
文件:DatabaseStatementTest.java
@MediumTest
public void testStatementConstraint() throws Exception {
mDatabase.execSQL("CREATE TABLE test (num INTEGER NOT NULL);");
SQLiteStatement statement = mDatabase.compileStatement("INSERT INTO test (num) VALUES (?)");
// Try to insert NULL, which violates the constraint
try {
statement.clearBindings();
statement.execute();
fail("expected exception not thrown");
} catch (SQLiteConstraintException e) {
// expected
}
// Make sure the statement can still be used
statement.bindLong(1, 1);
statement.execute();
statement.close();
Cursor c = mDatabase.query("test", null, null, null, null, null, null);
int numCol = c.getColumnIndexOrThrow("num");
c.moveToFirst();
long num = c.getLong(numCol);
assertEquals(1, num);
c.close();
}
项目:2016.2-MissaoNascente
文件:AchievementController.java
public boolean insertAchievementExplorer(final Context preferenceContext, String email, int idAchievement) {
try{
setAction(false);
AchievementExplorerRequest achievementExplorerRequest = new AchievementExplorerRequest(email, idAchievement);
achievementExplorerRequest.requestUpdateAchievements(preferenceContext, new AchievementExplorerRequest.Callback() {
@Override
public void callbackResponse(boolean response) {
setResponse(true);
setAction(true);
}
@Override
public void callbackResponse(List<Achievement> achievements) {}
});
}catch(SQLiteConstraintException exception){
exception.printStackTrace();
}
return true;
}
项目:2016.2-MissaoNascente
文件:ExplorerController.java
public boolean insertExplorerElement(final Context preferenceContext, String email, int idElement, String userImage, String catchDate) {
try{
setAction(false);
ElementExplorerRequest elementExplorerRequest = new ElementExplorerRequest(email,idElement,userImage,catchDate);
elementExplorerRequest.requestUpdateElements(preferenceContext, new ElementExplorerRequest.Callback() {
@Override
public void callbackResponse(boolean response) {
setResponse(true);
setAction(true);
}
MainController mainController = new MainController();
@Override
public void callbackResponse(List<Element> elements) {}
});
}catch(SQLiteConstraintException exception){
throw exception;
}
return true;
}
项目:GankIO
文件:DBTools.java
public static boolean insert(DBHelper dbHelper, NewGankData.Results data) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(Constants.DB_ITEM_DESC, data.getDesc());
values.put(Constants.DB_ITEM_TYPE, data.getType());
values.put(Constants.DB_ITEM_URL, data.getUrl());
db.insert(Constants.DB_TABLE_NAME, null, values);
db.setTransactionSuccessful();
return true;
} catch (SQLiteConstraintException e) {
LogUtils.e("DBTools -> insert", "insert data error");
return false;
} finally {
db.endTransaction();
}
}
项目:SecureSmartHome
文件:UserManagementController.java
/**
* Add a new UserDevice.
*
* @param userDevice The new UserDevice.
*/
public void addUserDevice(UserDevice userDevice) throws DatabaseControllerException {
try {
databaseConnector.executeSql("insert into "
+ DatabaseContract.UserDevice.TABLE_NAME
+ " (" + DatabaseContract.UserDevice.COLUMN_NAME + ","
+ DatabaseContract.UserDevice.COLUMN_FINGERPRINT + ","
+ DatabaseContract.UserDevice.COLUMN_GROUP_ID + ") values (?, ?,("
+ DatabaseContract.SqlQueries.GROUP_ID_FROM_NAME_SQL_QUERY + "))",
new String[]{userDevice.getName(), userDevice.getUserDeviceID().getIDString(),
userDevice.getInGroup()});
} catch (SQLiteConstraintException sqlce) {
throw new DatabaseControllerException(
"Either the given Group does not exist in the database"
+ " or a UserDevice already has the given name or fingerprint.", sqlce);
}
}
项目:SecureSmartHome
文件:HolidayController.java
/**
* Add a new action to the database.
*
* @param action Action to be added to the database.
* @param moduleName Module where the action occurs.
* @param timestamp The timestamp of the action.
*/
public void addHolidayLogEntry(String action, String moduleName, long timestamp) throws UnknownReferenceException {
if (Strings.isNullOrEmpty(moduleName)) {
databaseConnector.executeSql(
"insert into " + DatabaseContract.HolidayLog.TABLE_NAME
+ " (" + DatabaseContract.HolidayLog.COLUMN_ACTION
+ ", " + DatabaseContract.HolidayLog.COLUMN_TIMESTAMP + ") values (?, ?)",
new String[]{action, String.valueOf(timestamp)}
);
} else {
try {
databaseConnector.executeSql(
"insert into " + DatabaseContract.HolidayLog.TABLE_NAME
+ " (" + DatabaseContract.HolidayLog.COLUMN_ACTION
+ ", " + DatabaseContract.HolidayLog.COLUMN_ELECTRONIC_MODULE_ID
+ ", " + DatabaseContract.HolidayLog.COLUMN_TIMESTAMP + ") values (?,("
+ DatabaseContract.SqlQueries.MODULE_ID_FROM_NAME_SQL_QUERY + "),?)",
new String[]{action, moduleName, String.valueOf(timestamp)}
);
} catch (SQLiteConstraintException sqlce) {
throw new UnknownReferenceException("The given module doesn't exist.", sqlce);
}
}
}
项目:SecureSmartHome
文件:SlaveController.java
/**
* Add a new Module.
*
* @param module Module to add.
*/
public void addModule(Module module) throws DatabaseControllerException {
try {
//Notice: Changed order of values to avoid having to concat twice!
databaseConnector.executeSql("insert into "
+ DatabaseContract.ElectronicModule.TABLE_NAME + " ("
+ DatabaseContract.ElectronicModule.COLUMN_GPIO_PIN + ", "
+ DatabaseContract.ElectronicModule.COLUMN_USB_PORT + ", "
+ DatabaseContract.ElectronicModule.COLUMN_WLAN_PORT + ", "
+ DatabaseContract.ElectronicModule.COLUMN_WLAN_USERNAME + ", "
+ DatabaseContract.ElectronicModule.COLUMN_WLAN_PASSWORD + ", "
+ DatabaseContract.ElectronicModule.COLUMN_WLAN_IP + ", "
+ DatabaseContract.ElectronicModule.COLUMN_MODULE_TYPE + ", "
+ DatabaseContract.ElectronicModule.COLUMN_CONNECTOR_TYPE + ", "
+ DatabaseContract.ElectronicModule.COLUMN_SLAVE_ID + ", "
+ DatabaseContract.ElectronicModule.COLUMN_NAME + ") values "
+ "(?, ?, ?, ?, ?, ?, ?, ?, (" + DatabaseContract.SqlQueries.SLAVE_ID_FROM_FINGERPRINT_SQL_QUERY + "), ?)",
ObjectArrays.concat(
createCombinedModulesAccessInformationFromSingle(module.getModuleAccessPoint()),
new String[]{module.getModuleType().toString(), module.getModuleAccessPoint().getType(),
module.getAtSlave().getIDString(), module.getName()}, String.class));
} catch (SQLiteConstraintException sqlce) {
throw new DatabaseControllerException("The given Slave does not exist in the database"
+ " or the name is already used by another Module", sqlce);
}
}
项目:SecureSmartHome
文件:PermissionController.java
/**
* Adds a new Permission to the database.
*
* @param permission Permission to add.
* @param moduleName Module the permission applies for.
*/
public void addPermission(de.unipassau.isl.evs.ssh.core.sec.Permission permission,
String moduleName) throws DatabaseControllerException {
try {
if (Strings.isNullOrEmpty(moduleName)) {
databaseConnector.executeSql("insert into "
+ DatabaseContract.Permission.TABLE_NAME
+ " (" + DatabaseContract.Permission.COLUMN_NAME + ")"
+ " values (?)", new String[] { permission.toString() }
);
} else {
databaseConnector.executeSql("insert into "
+ DatabaseContract.Permission.TABLE_NAME
+ " (" + DatabaseContract.Permission.COLUMN_NAME
+ ", " + DatabaseContract.Permission.COLUMN_ELECTRONIC_MODULE_ID + ")"
+ "values (?, (" + DatabaseContract.SqlQueries.MODULE_ID_FROM_NAME_SQL_QUERY + "))",
new String[] { permission.toString(), moduleName }
);
}
} catch (SQLiteConstraintException sqlce) {
throw new DatabaseControllerException("Either the name-module combination is already exists in the database"
+ " or the given module doesn't exist.", sqlce);
}
}
项目:HighLite
文件:SQLiteOperatorTest.java
@Test
public void testOnUpgradeWithColumnChangeToNotNull() throws Exception {
getHelperInstance()
.getReadableDatabase()
.execSQL("CREATE TABLE testTable3 ("
+ " `xx` INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " `str` TEXT,"
+ " `unique` UNIQUE,"
+ " `foreign` INTEGER,"
+ " FOREIGN KEY(`foreign`) REFERENCES test_table(`unique`)"
+ ");"
);
SQLiteOperator<TestTable3> operator = SQLiteOperator.from(getContext(), TestTable3.class);
TestTable3 t = new TestTable3();
operator.save(t).executeBlocking();
operator.delete(t).executeBlocking();
getHelperInstance().onUpgrade(getHelperInstance().getWritableDatabase(), 1, 2);
exception.expect(SQLiteConstraintException.class);
operator.save(new TestTable3()).executeBlocking();
}
项目:HighLite
文件:SQLiteOperatorTest.java
@Test
public void testOnUpgradeWithColumnChangeToUnique() throws Exception {
getHelperInstance()
.getReadableDatabase()
.execSQL("CREATE TABLE testTable3 ("
+ " `xx` INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " `str` TEXT,"
+ " `unique` TEXT,"
+ " `foreign` INTEGER,"
+ " FOREIGN KEY(`foreign`) REFERENCES test_table(`unique`)"
+ ");"
);
SQLiteOperator<TestTable3> operator = SQLiteOperator.from(getContext(), TestTable3.class);
getHelperInstance().onUpgrade(getHelperInstance().getWritableDatabase(), 1, 2);
exception.expect(SQLiteConstraintException.class);
TestTable3 t = new TestTable3();
t.str = "not null";
t.unique = "a";
operator.save(t).executeBlocking();
t = new TestTable3();
t.str = "xxx";
t.unique = "a";
operator.save(t).executeBlocking();
}
项目:privacy-friendly-notes
文件:DbAccess.java
/**
* Inserts a new category into the database.
* @param c the current context.
* @param name the name of the category
*/
public static boolean addCategory(Context c, String name) {
boolean success = true;
DbOpenHelper dbHelper = new DbOpenHelper(c);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CategoryEntry.COLUMN_NAME, name.trim());
try {
db.insertOrThrow(CategoryEntry.TABLE_NAME, null, values);
} catch (SQLiteConstraintException e) {
success = false;
}
db.close();
return success;
}
项目:journal
文件:DatabaseHelper.java
/**
* Insert a news feed into the database
* @param newsFeed the news feed to add to the database
* @param category the title of the category
* @return true if the news feed was successfully inserted, false otherwise
*/
public boolean insertNewsFeed(NewsFeed newsFeed, String category) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseContract.NewsFeed.COLUMN_NAME_LABEL, newsFeed.getLabel());
values.put(DatabaseContract.NewsFeed.COLUMN_NAME_LINK, newsFeed.getLink());
values.put(DatabaseContract.NewsFeed.COLUMN_NAME_CATEGORY, category);
try {
db.insertWithOnConflict(DatabaseContract.NewsFeed.TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_ABORT);
} catch (SQLiteConstraintException e) {
Log.d("DB", "Conflict on insertion");
return false;
}
return true;
}
项目:journal
文件:DatabaseHelper.java
/**
* Insert a news category into the database
* @param newsCategory the news category to add to the database
* @return true if the news category was successfully inserted, false otherwise
*/
public boolean insertNewsCategory(NewsCategory newsCategory) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseContract.NewsCategory.COLUMN_NAME_TITLE, newsCategory.getTitle());
try {
db.insertWithOnConflict(DatabaseContract.NewsCategory.TABLE_NAME, null, values, SQLiteDatabase
.CONFLICT_ABORT);
} catch (SQLiteConstraintException e) {
Log.d("DB", "Conflict on insertion");
return false;
}
for (NewsFeed newsFeed : newsCategory.getFeeds()) {
insertNewsFeed(newsFeed, newsCategory.getTitle());
}
return true;
}
项目:journal
文件:DatabaseHelper.java
/**
* Remove a news category from the database
* @param newsCategory the news category to remove
* @return true if the news category was successfully removed, false otherwise
*/
public boolean removeNewsCategory(NewsCategory newsCategory) {
SQLiteDatabase db = getWritableDatabase();
for (NewsFeed newsFeed : newsCategory.getFeeds()) {
removeNewsFeed(newsFeed.getLabel());
}
try {
db.delete(DatabaseContract.NewsCategory.TABLE_NAME, "title = ?", new String[]{newsCategory.getTitle()});
} catch (SQLiteConstraintException e) {
Log.d("DB", "Conflict on deletion");
return false;
}
return true;
}
项目:ESP8266-IOT-Android
文件:DatabaseHandler_Data.java
public void addDataStore(DataStore_Data Data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, Data.getID()); // Data ID
values.put(KEY_DEVID, Data.getDevID()); // Device ID
values.put(KEY_ADDRESS, Data.getAddress()); // Data Address
values.put(KEY_FUNC, Data.getFunction()); // Data Function
values.put(KEY_STATUS, Data.getStatus()); // Data Status
values.put(KEY_ACTIV, Data.getisActive()); // Data Active
// Inserting Row
db.insert(TABLE_DataStoreS, null, values);
try {
db.insertOrThrow(TABLE_DataStoreS, null, values);
} catch (SQLiteConstraintException e) {
Log.e(TAG, "Database insert error try update..");
db.update(TABLE_DataStoreS, values, KEY_ID + " = ?", new String[]{String.valueOf(Data.getID())});
Log.d(TAG, "Success");
}
db.close(); // Closing database connection
}
项目:ODK-Liberia
文件:ActivityLogger.java
private void insertContentValues(ContentValues cv, FormIndex index) {
synchronized(mScrollActions) {
try {
while ( !mScrollActions.isEmpty() ) {
ContentValues scv = mScrollActions.removeFirst();
mDb.insert(DATABASE_TABLE, null, scv);
}
if ( cv != null ) {
String idx = "";
if ( index != null ) {
idx = getXPath(index);
}
cv.put(QUESTION,idx);
mDb.insert(DATABASE_TABLE, null, cv);
}
} catch (SQLiteConstraintException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
项目:soulissapp
文件:SoulissTypical.java
/**
* Decide come interpretare gli out e logga
*/
public void logTypical() {
ContentValues values = new ContentValues();
// wrap values from object
values.put(SoulissDBOpenHelper.COLUMN_LOG_NODE_ID, getNodeId());
values.put(SoulissDBOpenHelper.COLUMN_LOG_DATE, Calendar.getInstance().getTime().getTime());
values.put(SoulissDBOpenHelper.COLUMN_LOG_SLOT, getSlot());
if (isSensor()) {
Log.d(it.angelic.soulissclient.Constants.TAG, getDefaultName() + " saving sensor loggi: " + ((ISoulissTypicalSensor) this).getOutputFloat());
values.put(SoulissDBOpenHelper.COLUMN_LOG_VAL, ((ISoulissTypicalSensor) this).getOutputFloat());
} else {
Log.d(it.angelic.soulissclient.Constants.TAG, getDefaultName() + " saving loggi: " + getOutput());
values.put(SoulissDBOpenHelper.COLUMN_LOG_VAL, getOutput());
}
try {
SoulissDBHelper.getDatabase().insert(SoulissDBOpenHelper.TABLE_LOGS, null, values);
} catch (SQLiteConstraintException e) {
// sensori NaN violano il constraint
Log.e(it.angelic.soulissclient.Constants.TAG, "error saving log: " + e);
}
}
项目:cowbird
文件:ProtocolDBContentProvider.java
@Override
public Uri insert(Uri uri, ContentValues values) {
ContentConstants.ProtocolURLs vrUrl = convertURIToProtocolURL(uri);
long rowId = -1;
switch (vrUrl) {
case URLProtocol:
rowId = db.getWritableDatabase().insert(Protocol.TABLE_NAME, null, values);
new BackupManager(getContext()).dataChanged();
break;
default:
throw new SQLiteConstraintException("Failed to switch insert protocol " + uri);
}
// If the insert succeeded, the row ID exists.
if (rowId > 0) {
// Creates a URI with the note ID pattern and the new row ID appended to it.
Uri noteUri = ContentConstants.getUriFor(vrUrl, rowId);
// Notifies observers registered against this provider that the data changed.
getContext().getContentResolver().notifyChange(noteUri, null);
return noteUri;
} else {
throw new SQLiteConstraintException("Failed to insert row into " + uri);
}
}
项目:aelf-dailyreadings
文件:AelfCacheHelper.java
private void onSqliteError(SQLiteException e) {
if (
e instanceof SQLiteBindOrColumnIndexOutOfRangeException ||
e instanceof SQLiteConstraintException ||
e instanceof SQLiteDatabaseCorruptException ||
e instanceof SQLiteDatatypeMismatchException
) {
// If a migration did not go well, the best we can do is drop the database and re-create
// it from scratch. This is hackish but should allow more or less graceful recoveries.
TrackHelper.track().event("Office", "cache.db.error").name("critical").value(1f).with(tracker);
Log.e(TAG, "Critical database error. Droping + Re-creating", e);
close();
ctx.deleteDatabase(DB_NAME);
} else {
// Generic error. Close + re-open
Log.e(TAG, "Datable "+e.getClass().getName()+". Closing + re-opening", e);
TrackHelper.track().event("Office", "cache.db.error").name(e.getClass().getName()).value(1f).with(tracker);
close();
}
}
项目:dhis2-android-sdk
文件:DataElementStoreShould.java
@Test(expected = SQLiteConstraintException.class)
public void throw_sqlite_constraint_exception_when_persist_a_data_element_with_invalid_option_set_foreign_key() {
String fakeOptionSetUid = "fake_option_set_uid";
store.insert(
UID,
CODE,
NAME,
DISPLAY_NAME,
date,
date,
SHORT_NAME,
DISPLAY_SHORT_NAME,
DESCRIPTION,
DISPLAY_DESCRIPTION,
VALUE_TYPE,
ZERO_IS_SIGNIFICANT,
AGGREGATION_OPERATOR,
FORM_NAME,
NUMBER_TYPE,
DOMAIN_TYPE,
DIMENSION,
DISPLAY_FORM_NAME,
fakeOptionSetUid,
null
);
}
项目:dhis2-android-sdk
文件:RelationshipStoreShould.java
@Test(expected = SQLiteConstraintException.class)
public void not_insert_relationship_in_data_base_when_insert_null() {
//Insert foreign keys in their respective tables:
ContentValues relationshipType = CreateRelationshipTypeUtils.create(
RELATIONSHIP_TYPE_ID,
RELATIONSHIP_TYPE
);
database().insert(RelationshipTypeModel.TABLE, null, relationshipType);
long rowId = store.insert(null, null, RELATIONSHIP_TYPE);
Cursor cursor = database().query(RelationshipModel.TABLE, RELATIONSHIP_PROJECTION,
null, null, null, null, null, null);
assertThat(rowId).isEqualTo(1L);
assertThatCursor(cursor).hasRow(null, null, RELATIONSHIP_TYPE).isExhausted();
}
项目:dhis2-android-sdk
文件:EventStoreShould.java
@Test(expected = SQLiteConstraintException.class)
public void throw_exception_after_persist_event_with_invalid_program_foreign_key() {
eventStore.insert(
EVENT_UID,
ENROLLMENT_UID,
date,
date,
CREATED_AT_CLIENT,
LAST_UPDATED_AT_CLIENT,
STATUS,
LATITUDE,
LONGITUDE,
WRONG_UID, //supply wrong uid
PROGRAM_STAGE,
ORGANISATION_UNIT,
date,
date,
date,
STATE,
ATTRIBUTE_CATEGORY_OPTION_UID,
ATTRIBUTE_OPTION_COMBO_UID,
TRACKED_ENTITY_INSTANCE
);
}
项目:dhis2-android-sdk
文件:EventStoreShould.java
@Test(expected = SQLiteConstraintException.class)
public void throw_exception_after_persist_event_with_invalid_program_stage_foreign_key() throws ParseException {
eventStore.insert(
EVENT_UID,
ENROLLMENT_UID,
date,
date,
CREATED_AT_CLIENT,
LAST_UPDATED_AT_CLIENT,
STATUS,
LATITUDE,
LONGITUDE,
PROGRAM,
WRONG_UID, //supply wrong uid
ORGANISATION_UNIT,
date,
date,
date,
STATE,
ATTRIBUTE_CATEGORY_OPTION_UID,
ATTRIBUTE_OPTION_COMBO_UID,
TRACKED_ENTITY_INSTANCE
);
}
项目:dhis2-android-sdk
文件:EventStoreShould.java
@Test(expected = SQLiteConstraintException.class)
public void throw_exception_after_persist_event_with_invalid_organisation_unit_foreign_key() {
eventStore.insert(
EVENT_UID,
ENROLLMENT_UID,
date,
date,
CREATED_AT_CLIENT,
LAST_UPDATED_AT_CLIENT,
STATUS,
LATITUDE,
LONGITUDE,
PROGRAM,
PROGRAM_STAGE,
WRONG_UID, //supply wrong uid
date,
date,
date,
STATE,
ATTRIBUTE_CATEGORY_OPTION_UID,
ATTRIBUTE_OPTION_COMBO_UID,
TRACKED_ENTITY_INSTANCE
);
}
项目:dhis2-android-sdk
文件:EventStoreShould.java
@Test(expected = SQLiteConstraintException.class)
public void throw_exception_after_persist_event_with_invalid_enrollment_foreign_key() {
eventStore.insert(
EVENT_UID,
WRONG_UID, // supply wrong uid
date,
date,
CREATED_AT_CLIENT,
LAST_UPDATED_AT_CLIENT,
STATUS,
LATITUDE,
LONGITUDE,
PROGRAM,
PROGRAM_STAGE,
ORGANISATION_UNIT,
date,
date,
date,
STATE,
ATTRIBUTE_CATEGORY_OPTION_UID,
ATTRIBUTE_OPTION_COMBO_UID,
TRACKED_ENTITY_INSTANCE
);
}
项目:dhis2-android-sdk
文件:ProgramStageDataElementStoreShould.java
@Test(expected = SQLiteConstraintException.class)
public void throw_sqlite_constraint_exception_when_insert_program_stage_data_element_with_invalid_foreign_key() {
String fakeDataElementId = "fake_data_element_id";
store.insert(
UID,
CODE,
NAME,
DISPLAY_NAME,
date,
date,
DISPLAY_IN_REPORTS,
COMPULSORY,
ALLOW_PROVIDED_ELSEWHERE,
SORT_ORDER,
ALLOW_FUTURE_DATE,
fakeDataElementId,
PROGRAM_STAGE,
null
);
}
项目:dhis2-android-sdk
文件:EnrollmentStoreShould.java
@Test(expected = SQLiteConstraintException.class)
public void throw_sqlite_constraint_exception_when_persist_enrollment_with_invalid_org_unit_foreign_key() {
store.insert(
UID,
date,
date,
CREATED_AT_CLIENT,
LAST_UPDATED_AT_CLIENT,
WRONG_UID, //supply wrong uid
PROGRAM,
date,
date,
FOLLOW_UP,
ENROLLMENT_STATUS,
TRACKED_ENTITY_INSTANCE,
LATITUDE,
LONGITUDE,
STATE
);
}
项目:dhis2-android-sdk
文件:EnrollmentStoreShould.java
@Test(expected = SQLiteConstraintException.class)
public void throw_sqlite_constraint_exception_when_persist_enrollment_with_invalid_program_foreign_key() {
store.insert(
UID,
date,
date,
CREATED_AT_CLIENT,
LAST_UPDATED_AT_CLIENT,
ORGANISATION_UNIT,
WRONG_UID, //supply wrong uid
date,
date,
FOLLOW_UP,
ENROLLMENT_STATUS,
TRACKED_ENTITY_INSTANCE,
LATITUDE,
LONGITUDE,
STATE
);
}
项目:dhis2-android-sdk
文件:EnrollmentStoreShould.java
@Test(expected = SQLiteConstraintException.class)
public void throw_sqlite_constraint_exception_persist_enrollment_with_invalid_tracked_entity_instance_foreign_key() {
store.insert(
UID,
date,
date,
CREATED_AT_CLIENT,
LAST_UPDATED_AT_CLIENT,
ORGANISATION_UNIT,
PROGRAM,
date,
date,
FOLLOW_UP,
ENROLLMENT_STATUS,
WRONG_UID, //supply wrong uid
LATITUDE,
LONGITUDE,
STATE
);
}
项目:android-gto-support
文件:AbstractDaoIT.java
@Test
public void testInsertPrimaryKeyConflictCompoundKey() throws Exception {
final TestDao dao = getDao();
// create object
final Compound orig = new Compound("1", "2", "orig", "orig");
dao.insert(orig);
// test PK conflict
final Compound conflict = new Compound("1", "2", "conflict", "conflict");
try {
dao.insert(conflict);
fail("There should have been a PK conflict");
} catch (final SQLiteConstraintException expected) {
// expected conflict, should be original
final Compound refresh = dao.refresh(conflict);
assertNotNull(refresh);
assertThat(refresh.id1, is(orig.id1));
assertThat(refresh.id2, is(orig.id2));
assertThat(refresh.data1, allOf(is(orig.data1), is(not(conflict.data1))));
assertThat(refresh.data2, allOf(is(orig.data2), is(not(conflict.data2))));
}
}
项目:SuperHeroes-Agenda
文件:BaseDatosContactos.java
public boolean insertarContacto(String nombre, String direccion, String telefono, String email,int miembrofacebook, int miembrotwitter, int miembrogoogle, int miembrolinkedin, int sexo, String tipocontacto, int imagen){
SQLiteDatabase db = getWritableDatabase();
if (db != null) {
ContentValues valores = new ContentValues();
valores.put("nombre", nombre);
valores.put("direccion", direccion);
valores.put("telefono", telefono);
valores.put("email", email);
valores.put("miembrofacebook", miembrofacebook);
valores.put("miembrotwitter", miembrotwitter);
valores.put("miembrogoogle", miembrogoogle);
valores.put("miembrolinkedin", miembrolinkedin);
valores.put("sexo", sexo);
valores.put("tipocontacto", tipocontacto);
valores.put("imagen", imagen);
//db.insert("contactos", null, valores);
try {
db.insertOrThrow(TABLA, null, valores); //TABLA por "contactos"
return true;
} catch (SQLiteConstraintException e) {
Log.d(TAG, "Fallo en la insercion: seguramente la clave ya existe.");
}
}
db.close();
return false;
}
项目:SuperHeroes-Agenda
文件:BaseDatosContactos.java
public boolean insertarContacto(SQLiteDatabase db, String nombre, String direccion, String telefono, String email,int miembrofacebook, int miembrotwitter, int miembrogoogle, int miembrolinkedin, int sexo, String tipocontacto, int imagen){
if (db != null) {
ContentValues valores = new ContentValues();
valores.put("nombre", nombre);
valores.put("direccion", direccion);
valores.put("telefono", telefono);
valores.put("email", email);
valores.put("miembrofacebook", miembrofacebook);
valores.put("miembrotwitter", miembrotwitter);
valores.put("miembrogoogle", miembrogoogle);
valores.put("miembrolinkedin", miembrolinkedin);
valores.put("sexo", sexo);
valores.put("tipocontacto", tipocontacto);
valores.put("imagen", imagen);
//db.insert("contactos", null, valores);
try {
db.insertOrThrow(TABLA, null, valores); //TABLA por "contactos"
return true;
} catch (SQLiteConstraintException e) {
Log.d(TAG, "Fallo en la insercion: seguramente la clave ya existe.");
}
}
return false;
}