下面列出了android.database.sqlite.SQLiteException#printStackTrace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static long getChangeCount(String tableName)
{
String selection = getSelectionForSync();
MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
SQLiteDatabase db = map.getDatabase(true);
try {
// From sources of DatabaseUtils.queryNumEntries()
String s = (!TextUtils.isEmpty(selection)) ? " where " + selection : "";
return DatabaseUtils.longForQuery(db, "select count(*) from " + tableName + s, null);
} catch (SQLiteException e) {
e.printStackTrace();
Log.d(TAG, e.getLocalizedMessage());
return 0;
}
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor != null) {
Set<String> mBookedPrograms = new HashSet();
while (cursor.moveToNext()) {
try {
int idx = cursor.getColumnIndexOrThrow(Field.MD5_ID);
if (idx != -1) {
mBookedPrograms.add(cursor.getString(idx));
}
} catch (SQLiteException e) {
e.printStackTrace();
return;
}
}
if (this.mAdapter != null) {
this.mAdapter.setBookedPrograms(mBookedPrograms);
}
}
}
protected static void deleteLayers(Activity activity)
{
MainApplication app = (MainApplication) activity.getApplication();
for (int i = app.getMap().getLayerCount() - 1; i >= 0; i--) {
ILayer layer = app.getMap().getLayer(i);
if (!layer.getPath().getName().equals(MainApplication.LAYER_OSM) && !layer.getPath()
.getName()
.equals(MainApplication.LAYER_A) && !layer.getPath()
.getName()
.equals(MainApplication.LAYER_B) && !layer.getPath()
.getName()
.equals(MainApplication.LAYER_C) && !layer.getPath()
.getName()
.equals(MainApplication.LAYER_TRACKS)) {
layer.delete();
}
}
try {
((MapContentProviderHelper) MapBase.getInstance()).getDatabase(false).execSQL("VACUUM");
} catch (SQLiteException e) {
e.printStackTrace();
}
}
public static <T> long count(Class<?> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) {
long result = -1;
String filter = (!TextUtils.isEmpty(whereClause)) ? " where " + whereClause : "";
SQLiteStatement sqliteStatement;
try {
sqliteStatement = getSugarDataBase().compileStatement("SELECT count(*) FROM " + NamingHelper.toSQLName(type) + filter);
} catch (SQLiteException e) {
e.printStackTrace();
return result;
}
if (whereArgs != null) {
for (int i = whereArgs.length; i != 0; i--) {
sqliteStatement.bindString(i, whereArgs[i - 1]);
}
}
try {
result = sqliteStatement.simpleQueryForLong();
} finally {
sqliteStatement.close();
}
return result;
}
public static long getEntriesCount(String tableName)
{
MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
SQLiteDatabase db = map.getDatabase(true);
try {
return DatabaseUtils.queryNumEntries(db, tableName);
} catch (SQLiteException e) {
e.printStackTrace();
Log.d(TAG, e.getLocalizedMessage());
return 0;
}
}
public synchronized LogEntry getEntryByID(long ID) {
LogEntry ret = null;
if (openRead()) {
Cursor c;
try {
c = mDB.rawQuery("SELECT * " + "FROM " + TrustDB.EVENT_TABLE + " " + "WHERE ID=" + ID + ";", null);
} catch (SQLiteException e) {
tryClose();
e.printStackTrace();
return null;
}
if (c != null && c.getCount() == 1) {
ret = new LogEntry();
c.moveToFirst();
ret.setTime(c.getLong(c.getColumnIndex("time")));
ret.setID(c.getInt(c.getColumnIndex("ID")));
ret.setType(c.getInt(c.getColumnIndex("type")));
String extra = c.getString(c.getColumnIndex("extra"));
ret.setExtra(extra.substring(1, extra.length() - 1));
c.close();
} else {
Log.w(mContext.getPackageName(), "getEntry cursos was either NULL or empty or more than one");
tryClose();
return null;
}
}
tryClose();
return ret;
}
public ArrayList<Integer> getUsersNotToNotify() {
try {
return getUsersNotToNotify(getReadableDatabase());
} catch (SQLiteException e) {
e.printStackTrace();
return new ArrayList<>();
}
}
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
if (mWritableDB == null || !mWritableDB.isOpen() || mWritableDB.isReadOnly()) {
try {
mWritableDB = super.getWritableDatabase();
} catch (SQLiteException e) {
mWritableDB = null;
Log.e(TAG, "getWritableDatabase(): Error", e);
e.printStackTrace();
}
}
return mWritableDB;
}
@Override
public synchronized SQLiteDatabase getReadableDatabase() {
if (mReadableDB == null || !mReadableDB.isOpen()) {
try {
mReadableDB = super.getReadableDatabase();
} catch (SQLiteException e) {
mReadableDB = null;
Log.e(TAG, "getReadableDatabase(): Error opening", e);
e.printStackTrace();
}
}
return mReadableDB;
}
private boolean getEntryFromDB(ComponentKey cacheKey, CacheEntry entry, boolean lowRes) {
Cursor c = null;
try {
c = mIconDb.query(
new String[]{lowRes ? IconDB.COLUMN_ICON_LOW_RES : IconDB.COLUMN_ICON,
IconDB.COLUMN_LABEL},
IconDB.COLUMN_COMPONENT + " = ? AND " + IconDB.COLUMN_USER + " = ?",
new String[]{cacheKey.componentName.flattenToString(),
Long.toString(mUserManager.getSerialNumberForUser(cacheKey.user))});
if (c.moveToNext()) {
entry.icon = loadIconNoResize(c, 0, lowRes ? mLowResOptions : null);
entry.isLowResIcon = lowRes;
entry.title = c.getString(1);
if (entry.title == null) {
entry.title = "";
entry.contentDescription = "";
} else {
entry.contentDescription = mUserManager.getBadgedLabelForUser(
entry.title, cacheKey.user);
}
return true;
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
if (c != null) {
c.close();
}
}
return false;
}
synchronized void ensureDatabase() {
if (mDb != null && mDb.isOpen()) {
return;
}
// Sometimes retrieving the database fails. We do 2 retries: first without database deletion
// and then with deletion.
for (int tries = 0; tries < 2; tries++) {
try {
if (tries > 0) {
//delete db and recreate
deleteDB();
}
mDb = getWritableDatabase();
break;
} catch (SQLiteException e) {
e.printStackTrace();
}
// Wait before retrying.
try {
Thread.sleep(SLEEP_TIME_MS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
if(mDb == null){
return;
}
createTableIfNotExists(mDb);
mDb.setMaximumSize(mMaximumDatabaseSize);
}
@Override
public SQLiteDatabase openOrCreateDatabase(
String name,
int mode,
SQLiteDatabase.CursorFactory factory)
{
SQLiteDatabase result = null;
try {
result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);
} catch (SQLiteException e) {
e.printStackTrace();
}
return result;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
if (newVersion == 7) {
new Settings(mContext).setUsersNotToNotifyWhenLive(getUsersNotToNotify(db));
}
} catch (SQLiteException e) {
e.printStackTrace();
}
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
//db.close();
}
public ArrayList<Integer> getUsersNotToNotify() {
try {
return getUsersNotToNotify(getReadableDatabase());
} catch (SQLiteException e) {
e.printStackTrace();
return new ArrayList<>();
}
}
private static void addEventToCalendar(Context context, Events event) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
return;
}
long calID = AppSettings.Notifications.getSelectedCalendar(context);
long startMillis;
long endMillis;
startMillis = event.beginAt.getTime();
endMillis = event.endAt.getTime();
ContentResolver cr = context.getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, startMillis);
values.put(CalendarContract.Events.DTEND, endMillis);
values.put(CalendarContract.Events.TITLE, event.name);
values.put(CalendarContract.Events.DESCRIPTION, event.description);
values.put(CalendarContract.Events.CALENDAR_ID, calID);
values.put(CalendarContract.Events.EVENT_LOCATION, event.location);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getDisplayName());
values.put(CalendarContract.Events.CUSTOM_APP_PACKAGE, BuildConfig.APPLICATION_ID);
values.put(CalendarContract.Events.CUSTOM_APP_URI, getEventUri(event.id));
try {
cr.insert(CalendarContract.Events.CONTENT_URI, values);
} catch (SQLiteException e) {
e.printStackTrace();
}
}
private void createDatabaseAndInitialize()
{
Log.d("Database", "Database initializing...");
SQLiteDatabase database = null;
try
{
database = activity.openOrCreateDatabase(DB_PATH, Context.MODE_PRIVATE, null);
database.setForeignKeyConstraintsEnabled(true);
// Drop previous tables
database.execSQL("DROP TABLE IF EXISTS " + WEIGHT_TABLE_NAME);
database.execSQL("DROP TABLE IF EXISTS " + USER_TABLE_NAME);
// Create new tables
database.execSQL(CREATE_USER_TABLE_QUERY);
database.execSQL(CREATE_WEIGHT_TABLE_QUERY);
// Add default user to users table, it will have id 1
database.execSQL("INSERT INTO " + USER_TABLE_NAME + " VALUES (1,'Default')");
}
catch (SQLiteException e)
{
// Unhandled exception!
Log.d("Database", "Exception in createDatabaseAndInitialize!");
e.printStackTrace();
System.exit(-1);
}
finally
{
Log.d("Database", "Database initialize finished!");
if ( database != null )
database.close();
}
}
private SQLiteDatabase hookDatabase(String name, int mode, CursorFactory cursorFactory) {
if (VERSION.SDK_INT >= 11) {
return super.openOrCreateDatabase(name, mode, cursorFactory);
}
SQLiteDatabase sQLiteDatabase = null;
try {
return super.openOrCreateDatabase(name, mode, cursorFactory);
} catch (SQLiteException e) {
e.printStackTrace();
if (Globals.getApplication().deleteDatabase(name)) {
return super.openOrCreateDatabase(name, mode, cursorFactory);
}
return sQLiteDatabase;
}
}
private void init(Context context) {
final BuildConfig.ORM orm = BuildConfig.ORM.RAW;
final RawOpenHelper openHelper = new RawOpenHelper(context, orm.getDbName(), null, orm.getDbVersion());
try {
mDB = openHelper.getWritableDatabase();
} catch (SQLiteException e) {
e.printStackTrace();
}
}
public void insert(List<RawObject> list) {
mDB.beginTransaction();
try {
for (RawObject object: list) {
mDB.insert(RawObject.TABLE_NAME, null, toCV(object));
}
mDB.setTransactionSuccessful();
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
mDB.endTransaction();
}
}
/**
* Saves the content of the table to the database given.
*/
public void save() {
SQLiteDatabase db = getWritableDatabase();
/* Create the table if necessary */
String create = "CREATE TABLE IF NOT EXISTS ";
create = create.concat(SaveDatabaseContract.SaveTableSchema.TABLE_NAME + " (");
create = create.concat(SaveDatabaseContract.SaveTableSchema.COLUMN_KEY + " STRING, ");
create = create.concat(SaveDatabaseContract.SaveTableSchema.COLUMN_VALUE + " BLOB, ");
create = create.concat(SaveDatabaseContract.SaveTableSchema.COLUMN_SAVE_NAME + " TEXT");
create = create.concat(") ");
db.execSQL(create);
/* Save content to the table. */
ContentValues content = new ContentValues();
Iterator<String> i = values.keySet().iterator();
while (i.hasNext()) {
String key = i.next();
Object value = values.get(key);
content.put(SaveDatabaseContract.SaveTableSchema.COLUMN_KEY, key);
content.put(SaveDatabaseContract.SaveTableSchema.COLUMN_SAVE_NAME, name);
if (value instanceof Integer) {
content.put(SaveDatabaseContract.SaveTableSchema.COLUMN_VALUE, (Integer) value);
}
else if (value instanceof Float) {
content.put(SaveDatabaseContract.SaveTableSchema.COLUMN_VALUE, (Float) value);
}
else if (value instanceof String) {
content.put(SaveDatabaseContract.SaveTableSchema.COLUMN_VALUE, (String) value);
}
try {
db.insertWithOnConflict(SaveDatabaseContract.SaveTableSchema.TABLE_NAME, null, content, SQLiteDatabase.CONFLICT_REPLACE);
} catch (SQLiteException e) {
Log.e("BobEngine", "Could not save values to the table \"" + SaveDatabaseContract.SaveTableSchema.TABLE_NAME + "\". Did the schema change?");
e.printStackTrace();
}
}
db.close();
}