use of android.database.sqlite.SQLiteException in project SeriesGuide by UweTrottmann.
the class AnalyticsTree method log.
@Override
protected void log(int priority, String tag, String message, Throwable t) {
if (priority == Log.ERROR) {
// remove any stack trace attached by Timber
if (message != null) {
int newLine = message.indexOf('\n');
if (newLine > 0) {
message = message.substring(0, newLine);
}
}
// special treatment for some exceptions
if (t instanceof TvdbException) {
TvdbException e = (TvdbException) t;
Utils.trackCustomEvent(context, CATEGORY_THETVDB_ERROR, tag + ": " + message, e.getMessage());
return;
} else if (t instanceof OAuthProblemException) {
// log trakt OAuth failures
OAuthProblemException e = (OAuthProblemException) t;
StringBuilder exceptionMessage = new StringBuilder();
if (!TextUtils.isEmpty(e.getError())) {
exceptionMessage.append(e.getError());
}
if (!TextUtils.isEmpty(e.getDescription())) {
exceptionMessage.append(", ").append(e.getDescription());
}
if (!TextUtils.isEmpty(e.getUri())) {
exceptionMessage.append(", ").append(e.getUri());
}
Utils.trackCustomEvent(context, "OAuth Error", tag + ": " + message, exceptionMessage.toString());
return;
} else if (t instanceof OAuthSystemException) {
// log trakt OAuth failures
OAuthSystemException e = (OAuthSystemException) t;
Utils.trackCustomEvent(context, "OAuth Error", tag + ": " + message, e.getMessage());
return;
}
}
// drop empty messages
if (message == null) {
return;
}
// drop debug and verbose logs
if (priority == Log.DEBUG || priority == Log.VERBOSE) {
return;
}
// transform priority into string
String level = null;
switch(priority) {
case Log.INFO:
level = "INFO";
break;
case Log.WARN:
level = "WARN";
break;
case Log.ERROR:
level = "ERROR";
break;
}
// finally log to crashlytics
Crashlytics.log(level + "/" + tag + ": " + message);
// track some non-fatal exceptions with crashlytics
if (priority == Log.ERROR) {
if (t instanceof SQLiteException) {
Crashlytics.logException(t);
}
}
}
use of android.database.sqlite.SQLiteException in project SeriesGuide by UweTrottmann.
the class SeriesGuideProvider method query.
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
if (LOGV) {
Timber.v("query(uri=%s, proj=%s)", uri, Arrays.toString(projection));
}
// always get writable database, might have to be upgraded
final SQLiteDatabase db = mDbHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch(match) {
case RENEW_FTSTABLE:
{
SeriesGuideDatabase.rebuildFtsTable(db);
return null;
}
case EPISODESEARCH:
{
if (selectionArgs == null) {
throw new IllegalArgumentException("selectionArgs must be provided for the Uri: " + uri);
}
return SeriesGuideDatabase.search(selection, selectionArgs, db);
}
case SEARCH_SUGGEST:
{
if (selectionArgs == null) {
throw new IllegalArgumentException("selectionArgs must be provided for the Uri: " + uri);
}
return SeriesGuideDatabase.getSuggestions(selectionArgs[0], db);
}
default:
{
// Most cases are handled with simple SelectionBuilder
final SelectionBuilder builder = buildSelection(uri, match);
Cursor query = null;
try {
query = builder.map(BaseColumns._COUNT, // support count base column
"count(*)").where(selection, selectionArgs).query(db, projection, sortOrder);
} catch (SQLiteException e) {
Timber.e(e, "Failed to query with uri=%s", uri);
}
if (query != null) {
//noinspection ConstantConditions
query.setNotificationUri(getContext().getContentResolver(), uri);
}
return query;
}
}
}
use of android.database.sqlite.SQLiteException in project SeriesGuide by UweTrottmann.
the class DBUtils method updateLatestEpisode.
/**
* Update next episode field and unwatched episode count for the given show. If no show id is
* passed, will update next episodes for all shows.
*
* @return If only one show was passed, the TVDb id of the new next episode. Otherwise -1.
*/
public static long updateLatestEpisode(Context context, Integer showTvdbIdToUpdate) {
// get a list of shows and their last watched episodes
Cursor shows;
try {
shows = context.getContentResolver().query(Shows.CONTENT_URI_WITH_LAST_EPISODE, LastWatchedEpisodeQuery.PROJECTION, showTvdbIdToUpdate != null ? Qualified.SHOWS_ID + "=" + showTvdbIdToUpdate : null, null, null);
} catch (SQLiteException e) {
shows = null;
Timber.e(e, "updateLatestEpisode: show query failed.");
postDatabaseError(e);
}
if (shows == null) {
// abort completely on query failure
Timber.e("Failed to update next episode values");
return -1;
}
final List<String[]> showsLastEpisodes = new ArrayList<>();
while (shows.moveToNext()) {
showsLastEpisodes.add(new String[] { // 0
shows.getString(LastWatchedEpisodeQuery.SHOW_TVDB_ID), // 1
shows.getString(LastWatchedEpisodeQuery.LAST_EPISODE_TVDB_ID), // 2
shows.getString(LastWatchedEpisodeQuery.LAST_EPISODE_SEASON), // 3
shows.getString(LastWatchedEpisodeQuery.LAST_EPISODE_NUMBER), shows.getString(LastWatchedEpisodeQuery.LAST_EPISODE_FIRST_RELEASE_MS) });
}
shows.close();
// pre-build next episode selection
final boolean isNoReleasedEpisodes = DisplaySettings.isNoReleasedEpisodes(context);
final String nextEpisodeSelection = buildNextEpisodeSelection(DisplaySettings.isHidingSpecials(context), isNoReleasedEpisodes);
// build updated next episode values for each show
int nextEpisodeTvdbId = -1;
final ContentValues newShowValues = new ContentValues();
final ArrayList<ContentProviderOperation> batch = new ArrayList<>();
final String currentTime = String.valueOf(TimeTools.getCurrentTime(context));
final boolean displayExactDate = DisplaySettings.isDisplayExactDate(context);
DisplaySettings.preventSpoilers(context);
for (String[] show : showsLastEpisodes) {
// STEP 1: get last watched episode details
final String showTvdbId = show[0];
final String lastEpisodeTvdbId = show[1];
String season = show[2];
String number = show[3];
String releaseTime = show[4];
if (TextUtils.isEmpty(lastEpisodeTvdbId) || season == null || number == null || releaseTime == null) {
// by default: no watched episodes, include all starting with special 0
season = "-1";
number = "-1";
releaseTime = String.valueOf(Long.MIN_VALUE);
}
// STEP 2: get episode released closest afterwards; or at the same time,
// but with a higher number
final String[] selectionArgs;
if (isNoReleasedEpisodes) {
// restrict to episodes with future release date
selectionArgs = new String[] { releaseTime, number, season, releaseTime, currentTime };
} else {
// restrict to episodes with any valid air date
selectionArgs = new String[] { releaseTime, number, season, releaseTime };
}
Cursor next;
try {
next = context.getContentResolver().query(Episodes.buildEpisodesOfShowUri(showTvdbId), NextEpisodesQuery.PROJECTION, nextEpisodeSelection, selectionArgs, NextEpisodesQuery.SORTORDER);
} catch (SQLiteException e) {
next = null;
Timber.e(e, "updateLatestEpisode: next episode query failed.");
postDatabaseError(e);
}
if (next == null) {
// abort completely on query failure
Timber.e("Failed to update next episode values");
return -1;
}
// STEP 3: build updated next episode values
if (next.moveToFirst()) {
final String nextEpisodeString;
int seasonNumber = next.getInt(NextEpisodesQuery.SEASON);
int episodeNumber = next.getInt(NextEpisodesQuery.NUMBER);
if (DisplaySettings.preventSpoilers(context)) {
// just the number, like '0x12'
nextEpisodeString = TextTools.getEpisodeNumber(context, seasonNumber, episodeNumber);
} else {
// next episode text, like '0x12 Episode Name'
nextEpisodeString = TextTools.getNextEpisodeString(context, seasonNumber, episodeNumber, next.getString(NextEpisodesQuery.TITLE));
}
// next release date text, e.g. "in 15 mins (Fri)"
long releaseTimeNext = next.getLong(NextEpisodesQuery.FIRST_RELEASE_MS);
Date actualRelease = TimeTools.applyUserOffset(context, releaseTimeNext);
String dateTime = displayExactDate ? TimeTools.formatToLocalDateShort(context, actualRelease) : TimeTools.formatToLocalRelativeTime(context, actualRelease);
final String nextReleaseDateString = context.getString(R.string.release_date_and_day, dateTime, TimeTools.formatToLocalDay(actualRelease));
nextEpisodeTvdbId = next.getInt(NextEpisodesQuery.ID);
newShowValues.put(Shows.NEXTEPISODE, nextEpisodeTvdbId);
newShowValues.put(Shows.NEXTAIRDATEMS, releaseTimeNext);
newShowValues.put(Shows.NEXTTEXT, nextEpisodeString);
newShowValues.put(Shows.NEXTAIRDATETEXT, nextReleaseDateString);
} else {
// no next episode, set empty values
nextEpisodeTvdbId = 0;
newShowValues.put(Shows.NEXTEPISODE, "");
newShowValues.put(Shows.NEXTAIRDATEMS, UNKNOWN_NEXT_RELEASE_DATE);
newShowValues.put(Shows.NEXTTEXT, "");
newShowValues.put(Shows.NEXTAIRDATETEXT, "");
}
next.close();
// STEP 4: get remaining episodes count
int unwatchedEpisodesCount = getUnwatchedEpisodesOfShow(context, showTvdbId);
newShowValues.put(Shows.UNWATCHED_COUNT, unwatchedEpisodesCount);
// update the show with the new next episode values
batch.add(ContentProviderOperation.newUpdate(Shows.buildShowUri(showTvdbId)).withValues(newShowValues).build());
newShowValues.clear();
}
try {
DBUtils.applyInSmallBatches(context, batch);
} catch (OperationApplicationException e) {
Timber.e(e, "Failed to update next episode values");
return -1;
}
return nextEpisodeTvdbId;
}
use of android.database.sqlite.SQLiteException in project LitePal by LitePalFramework.
the class UpdateUsingUpdateMethodTest method testUpdateAllWithStaticUpdateButWrongConditions.
public void testUpdateAllWithStaticUpdateButWrongConditions() {
ContentValues values = new ContentValues();
values.put("name", "Dustee");
try {
DataSupport.updateAll(Student.class, values, "name = 'Dustin'", "aaa");
fail();
} catch (DataSupportException e) {
assertEquals("The parameters in conditions are incorrect.", e.getMessage());
}
try {
DataSupport.updateAll(Student.class, values, null, null);
fail();
} catch (DataSupportException e) {
assertEquals("The parameters in conditions are incorrect.", e.getMessage());
}
try {
DataSupport.updateAll(Student.class, values, "address = ?", "HK");
fail();
} catch (SQLiteException e) {
}
}
use of android.database.sqlite.SQLiteException in project XPrivacy by M66B.
the class PrivacyService method storeUsageData.
private void storeUsageData(final PRestriction restriction, String secret, final PRestriction mresult) throws RemoteException {
// Check if enabled
final int userId = Util.getUserId(restriction.uid);
if (getSettingBool(userId, PrivacyManager.cSettingUsage, true) && !getSettingBool(restriction.uid, PrivacyManager.cSettingNoUsageData, false)) {
// Check secret
boolean allowed = true;
if (Util.getAppId(Binder.getCallingUid()) != getXUid()) {
if (mSecret == null || !mSecret.equals(secret)) {
allowed = false;
Util.log(null, Log.WARN, "Invalid secret restriction=" + restriction);
}
}
if (allowed) {
mExecutor.execute(new Runnable() {
public void run() {
try {
if (XActivityManagerService.canWriteUsageData()) {
SQLiteDatabase dbUsage = getDbUsage();
if (dbUsage == null)
return;
// Parameter
String extra = "";
if (restriction.extra != null)
if (getSettingBool(userId, PrivacyManager.cSettingParameters, false))
extra = restriction.extra;
// Value
if (restriction.value != null)
if (!getSettingBool(userId, PrivacyManager.cSettingValues, false))
restriction.value = null;
mLockUsage.writeLock().lock();
try {
dbUsage.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("uid", restriction.uid);
values.put("restriction", restriction.restrictionName);
values.put("method", restriction.methodName);
values.put("restricted", mresult.restricted);
values.put("time", new Date().getTime());
values.put("extra", extra);
if (restriction.value == null)
values.putNull("value");
else
values.put("value", restriction.value);
dbUsage.insertWithOnConflict(cTableUsage, null, values, SQLiteDatabase.CONFLICT_REPLACE);
dbUsage.setTransactionSuccessful();
} finally {
dbUsage.endTransaction();
}
} finally {
mLockUsage.writeLock().unlock();
}
}
} catch (SQLiteException ex) {
Util.log(null, Log.WARN, ex.toString());
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
});
}
}
}
Aggregations