android.database.DatabaseUtils Java Examples

The following examples show how to use android.database.DatabaseUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ContentProviderNative.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public String[] getStreamTypes(Uri url, String mimeTypeFilter) throws RemoteException
{
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    try {
        data.writeInterfaceToken(IContentProvider.descriptor);

        url.writeToParcel(data, 0);
        data.writeString(mimeTypeFilter);

        mRemote.transact(IContentProvider.GET_STREAM_TYPES_TRANSACTION, data, reply, 0);

        DatabaseUtils.readExceptionFromParcel(reply);
        String[] out = reply.createStringArray();
        return out;
    } finally {
        data.recycle();
        reply.recycle();
    }
}
 
Example #2
Source File: FileUtils.java    From secrecy with Apache License 2.0 6 votes vote down vote up
/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 * @author paulburke
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            if (DEBUG)
                DatabaseUtils.dumpCursor(cursor);

            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example #3
Source File: Storage.java    From Clip-Stack with MIT License 6 votes vote down vote up
private String sqliteEscape(String keyWord) {
        return DatabaseUtils.sqlEscapeString(keyWord);
//        if ("".equals(keyWord) || keyWord == null) {
//            return keyWord;
//        }
//        return keyWord
//                .replace("'", "''")
//                .replace("/", "//")
//                .replace("[", "/[")
//                .replace("]", "/]")
//                .replace("%", "/%")
//                .replace("&", "/&")
//                .replace("_", "/_")
//                .replace("(", "/(")
//                .replace(")", "/)")
//                ;
    }
 
Example #4
Source File: ContentProviderNative.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public int update(String callingPkg, Uri url, ContentValues values, String selection,
        String[] selectionArgs) throws RemoteException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    try {
        data.writeInterfaceToken(IContentProvider.descriptor);

        data.writeString(callingPkg);
        url.writeToParcel(data, 0);
        values.writeToParcel(data, 0);
        data.writeString(selection);
        data.writeStringArray(selectionArgs);

        mRemote.transact(IContentProvider.UPDATE_TRANSACTION, data, reply, 0);

        DatabaseUtils.readExceptionFromParcel(reply);
        int count = reply.readInt();
        return count;
    } finally {
        data.recycle();
        reply.recycle();
    }
}
 
Example #5
Source File: ExportBackupService.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
private static void appendValues(final Cursor cursor, final StringBuilder builder, final int skipColumn) {
    builder.append("(");
    for (int i = 0; i < cursor.getColumnCount(); ++i) {
        if (i == skipColumn) {
            continue;
        }
        if (i != 0) {
            builder.append(',');
        }
        final String value = cursor.getString(i);
        if (value == null) {
            builder.append("NULL");
        } else if (value.matches("[0-9]+")) {
            builder.append(value);
        } else {
            DatabaseUtils.appendEscapedSQLString(builder, value);
        }
    }
    builder.append(")");

}
 
Example #6
Source File: ContentProviderNative.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public ContentProviderResult[] applyBatch(String callingPkg,
        ArrayList<ContentProviderOperation> operations)
                throws RemoteException, OperationApplicationException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    try {
        data.writeInterfaceToken(IContentProvider.descriptor);
        data.writeString(callingPkg);
        data.writeInt(operations.size());
        for (ContentProviderOperation operation : operations) {
            operation.writeToParcel(data, 0);
        }
        mRemote.transact(IContentProvider.APPLY_BATCH_TRANSACTION, data, reply, 0);

        DatabaseUtils.readExceptionWithOperationApplicationExceptionFromParcel(reply);
        final ContentProviderResult[] results =
                reply.createTypedArray(ContentProviderResult.CREATOR);
        return results;
    } finally {
        data.recycle();
        reply.recycle();
    }
}
 
Example #7
Source File: ContentProviderNative.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public int bulkInsert(String callingPkg, Uri url, ContentValues[] values) throws RemoteException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    try {
        data.writeInterfaceToken(IContentProvider.descriptor);

        data.writeString(callingPkg);
        url.writeToParcel(data, 0);
        data.writeTypedArray(values, 0);

        mRemote.transact(IContentProvider.BULK_INSERT_TRANSACTION, data, reply, 0);

        DatabaseUtils.readExceptionFromParcel(reply);
        int count = reply.readInt();
        return count;
    } finally {
        data.recycle();
        reply.recycle();
    }
}
 
Example #8
Source File: ContentProviderNative.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public Uri uncanonicalize(String callingPkg, Uri url) throws RemoteException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    try {
        data.writeInterfaceToken(IContentProvider.descriptor);

        data.writeString(callingPkg);
        url.writeToParcel(data, 0);

        mRemote.transact(IContentProvider.UNCANONICALIZE_TRANSACTION, data, reply, 0);

        DatabaseUtils.readExceptionFromParcel(reply);
        Uri out = Uri.CREATOR.createFromParcel(reply);
        return out;
    } finally {
        data.recycle();
        reply.recycle();
    }
}
 
Example #9
Source File: FileUtils.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context       The context.
 * @param uri           The Uri to query.
 * @param selection     (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 * @author paulburke
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            if (DEBUG)
                DatabaseUtils.dumpCursor(cursor);

            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example #10
Source File: SQLiteSession.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Performs special reinterpretation of certain SQL statements such as "BEGIN",
 * "COMMIT" and "ROLLBACK" to ensure that transaction state invariants are
 * maintained.
 *
 * This function is mainly used to support legacy apps that perform their
 * own transactions by executing raw SQL rather than calling {@link #beginTransaction}
 * and the like.
 *
 * @param sql The SQL statement to execute.
 * @param bindArgs The arguments to bind, or null if none.
 * @param connectionFlags The connection flags to use if a connection must be
 * acquired by this operation.  Refer to {@link SQLiteConnectionPool}.
 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
 * @return True if the statement was of a special form that was handled here,
 * false otherwise.
 *
 * @throws SQLiteException if an error occurs, such as a syntax error
 * or invalid number of bind arguments.
 * @throws OperationCanceledException if the operation was canceled.
 */
private boolean executeSpecial(String sql, Object[] bindArgs, int connectionFlags,
        CancellationSignal cancellationSignal) {
    if (cancellationSignal != null) {
        cancellationSignal.throwIfCanceled();
    }

    final int type = DatabaseUtils.getSqlStatementType(sql);
    switch (type) {
        case DatabaseUtils.STATEMENT_BEGIN:
            beginTransaction(TRANSACTION_MODE_EXCLUSIVE, null, connectionFlags,
                    cancellationSignal);
            return true;

        case DatabaseUtils.STATEMENT_COMMIT:
            setTransactionSuccessful();
            endTransaction(cancellationSignal);
            return true;

        case DatabaseUtils.STATEMENT_ABORT:
            endTransaction(cancellationSignal);
            return true;
    }
    return false;
}
 
Example #11
Source File: ContentProviderNative.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public boolean refresh(String callingPkg, Uri url, Bundle args, ICancellationSignal signal)
        throws RemoteException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    try {
        data.writeInterfaceToken(IContentProvider.descriptor);

        data.writeString(callingPkg);
        url.writeToParcel(data, 0);
        data.writeBundle(args);
        data.writeStrongBinder(signal != null ? signal.asBinder() : null);

        mRemote.transact(IContentProvider.REFRESH_TRANSACTION, data, reply, 0);

        DatabaseUtils.readExceptionFromParcel(reply);
        int success = reply.readInt();
        return (success == 0);
    } finally {
        data.recycle();
        reply.recycle();
    }
}
 
Example #12
Source File: ContentProviderNative.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public Bundle call(String callingPkg, String method, String request, Bundle args)
        throws RemoteException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    try {
        data.writeInterfaceToken(IContentProvider.descriptor);

        data.writeString(callingPkg);
        data.writeString(method);
        data.writeString(request);
        data.writeBundle(args);

        mRemote.transact(IContentProvider.CALL_TRANSACTION, data, reply, 0);

        DatabaseUtils.readExceptionFromParcel(reply);
        Bundle bundle = reply.readBundle();
        return bundle;
    } finally {
        data.recycle();
        reply.recycle();
    }
}
 
Example #13
Source File: QiscusDataBaseHelper.java    From qiscus-sdk-android with Apache License 2.0 6 votes vote down vote up
@Override
public QiscusChatRoom getChatRoomWithUniqueId(String uniqueId) {
    String query = "SELECT * FROM "
            + QiscusDb.RoomTable.TABLE_NAME + " WHERE "
            + QiscusDb.RoomTable.COLUMN_UNIQUE_ID + " = " + DatabaseUtils.sqlEscapeString(uniqueId);

    Cursor cursor = sqLiteReadDatabase.rawQuery(query, null);

    if (cursor.moveToNext()) {
        QiscusChatRoom qiscusChatRoom = QiscusDb.RoomTable.parseCursor(cursor);
        qiscusChatRoom.setMember(getRoomMembers(qiscusChatRoom.getId()));
        QiscusComment latestComment = getLatestComment(qiscusChatRoom.getId());
        if (latestComment != null) {
            qiscusChatRoom.setLastComment(latestComment);
        }
        cursor.close();
        return qiscusChatRoom;
    } else {
        cursor.close();
        return null;
    }
}
 
Example #14
Source File: ContentProviderNative.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri url, String mimeType,
        Bundle opts, ICancellationSignal signal) throws RemoteException, FileNotFoundException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    try {
        data.writeInterfaceToken(IContentProvider.descriptor);

        data.writeString(callingPkg);
        url.writeToParcel(data, 0);
        data.writeString(mimeType);
        data.writeBundle(opts);
        data.writeStrongBinder(signal != null ? signal.asBinder() : null);

        mRemote.transact(IContentProvider.OPEN_TYPED_ASSET_FILE_TRANSACTION, data, reply, 0);

        DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(reply);
        int has = reply.readInt();
        AssetFileDescriptor fd = has != 0
                ? AssetFileDescriptor.CREATOR.createFromParcel(reply) : null;
        return fd;
    } finally {
        data.recycle();
        reply.recycle();
    }
}
 
Example #15
Source File: ArtistDataSource.java    From PlayMusicExporter with MIT License 6 votes vote down vote up
/**
 * Prepare the where command and adds the global settings
 * @param where The where command
 * @return The new where command
 */
private String prepareWhere(String where) {
    // Ignore non-PlayMusic tracks
    where = combineWhere(where, "LocalCopyType != 300");

    // Loads only offline tracks
    if (mOfflineOnly)
        where = combineWhere(where, "LocalCopyPath IS NOT NULL");

    // Search only items which contains the key
    if (!TextUtils.isEmpty(mSearchKey)) {
        String searchKey = DatabaseUtils.sqlEscapeString("%" + mSearchKey + "%");

        where = combineWhere(where, "(" + COLUMN_ARTIST + " LIKE " + searchKey + ")");
    }

    return where;
}
 
Example #16
Source File: QiscusDataBaseHelper.java    From qiscus-sdk-android with Apache License 2.0 6 votes vote down vote up
@Override
public void updateRoomMember(long roomId, QiscusRoomMember qiscusRoomMember, String distinctId) {
    distinctId = distinctId == null ? "default" : distinctId;
    String where = QiscusDb.RoomMemberTable.COLUMN_ROOM_ID + " = " + roomId + " AND "
            + QiscusDb.RoomMemberTable.COLUMN_USER_EMAIL + " = " + DatabaseUtils.sqlEscapeString(qiscusRoomMember.getEmail());

    sqLiteWriteDatabase.beginTransactionNonExclusive();
    try {
        sqLiteWriteDatabase.update(QiscusDb.RoomMemberTable.TABLE_NAME,
                QiscusDb.RoomMemberTable.toContentValues(roomId, distinctId, qiscusRoomMember), where, null);
        sqLiteWriteDatabase.setTransactionSuccessful();
    } catch (Exception e) {
        QiscusErrorLogger.print(e);
    } finally {
        sqLiteWriteDatabase.endTransaction();
    }

    addOrUpdate(qiscusRoomMember);
}
 
Example #17
Source File: FilterDBTask.java    From iBeebo with GNU General Public License v3.0 6 votes vote down vote up
public static void addFilterKeyword(int type, Collection<String> words) {

        DatabaseUtils.InsertHelper ih = new DatabaseUtils.InsertHelper(getWsd(), FilterTable.TABLE_NAME);
        final int nameColumn = ih.getColumnIndex(FilterTable.NAME);
        final int activeColumn = ih.getColumnIndex(FilterTable.ACTIVE);
        final int typeColumn = ih.getColumnIndex(FilterTable.TYPE);
        try {
            getWsd().beginTransaction();
            for (String word : words) {
                ih.prepareForInsert();

                ih.bind(nameColumn, word);
                ih.bind(activeColumn, true);
                ih.bind(typeColumn, type);

                ih.execute();
            }

            getWsd().setTransactionSuccessful();
        } catch (SQLException e) {
        } finally {
            getWsd().endTransaction();
            ih.close();
        }

    }
 
Example #18
Source File: ContactsListFragment.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    StringBuilder buf = new StringBuilder();

    if (mSearchString != null) {
        buf.append('(');
        buf.append(Imps.Contacts.NICKNAME);
        buf.append(" LIKE ");
        DatabaseUtils.appendValueToSql(buf, "%" + mSearchString + "%");
        buf.append(" OR ");
        buf.append(Imps.Contacts.USERNAME);
        buf.append(" LIKE ");
        DatabaseUtils.appendValueToSql(buf, "%" + mSearchString + "%");
        buf.append(')');
        buf.append(" AND ");
    }

    buf.append(Imps.Contacts.TYPE).append('=').append(mType);
 //   buf.append(" ) GROUP BY(" + Imps.Contacts.USERNAME);

    CursorLoader loader = new CursorLoader(getActivity(), mUri, ContactListItem.CONTACT_PROJECTION,
            buf == null ? null : buf.toString(), null, Imps.Contacts.SUB_AND_ALPHA_SORT_ORDER);

    return loader;
}
 
Example #19
Source File: FilterDBTask.java    From iBeebo with GNU General Public License v3.0 6 votes vote down vote up
public static void addFilterKeyword(int type, Collection<String> words) {

        DatabaseUtils.InsertHelper ih = new DatabaseUtils.InsertHelper(getWsd(), FilterTable.TABLE_NAME);
        final int nameColumn = ih.getColumnIndex(FilterTable.NAME);
        final int activeColumn = ih.getColumnIndex(FilterTable.ACTIVE);
        final int typeColumn = ih.getColumnIndex(FilterTable.TYPE);
        try {
            getWsd().beginTransaction();
            for (String word : words) {
                ih.prepareForInsert();

                ih.bind(nameColumn, word);
                ih.bind(activeColumn, true);
                ih.bind(typeColumn, type);

                ih.execute();
            }

            getWsd().setTransactionSuccessful();
        } catch (SQLException e) {
        } finally {
            getWsd().endTransaction();
            ih.close();
        }

    }
 
Example #20
Source File: Queries.java    From NClientV2 with Apache License 2.0 6 votes vote down vote up
private static void dumpTable(String name,FileWriter sb) throws IOException{

            String query="SELECT * FROM "+ name;
            Cursor c=db.rawQuery(query,null);
            sb.write("DUMPING: ");
            sb.write(name);
            sb.write(" count: ");
            sb.write(""+c.getCount());
            sb.write(": ");
            if(c.moveToFirst()){
                do{
                    sb.write(DatabaseUtils.dumpCurrentRowToString(c));
                }while(c.moveToNext());
            }
            c.close();
            sb.append("END DUMPING\n");
        }
 
Example #21
Source File: AccountsDb.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
int calculateDebugTableInsertionPoint() {
    SQLiteDatabase db = mDeDatabase.getReadableDatabase();
    String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + TABLE_DEBUG;
    int size = (int) DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
    if (size < MAX_DEBUG_DB_SIZE) {
        return size;
    }

    // This query finds the smallest timestamp value (and if 2 records have
    // same timestamp, the choose the lower id).
    queryCountDebugDbRows = "SELECT " + DEBUG_TABLE_KEY +
            " FROM " + TABLE_DEBUG +
            " ORDER BY "  + DEBUG_TABLE_TIMESTAMP + "," + DEBUG_TABLE_KEY +
            " LIMIT 1";
    return (int) DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
}
 
Example #22
Source File: FileUtils.java    From qiniu-lab-android with MIT License 6 votes vote down vote up
/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context       The context.
 * @param uri           The Uri to query.
 * @param selection     (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 * @author paulburke
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            if (DEBUG)
                DatabaseUtils.dumpCursor(cursor);

            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example #23
Source File: BookDatabaseHelper.java    From IslamicLibraryAndroid with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param titleId  the title id to return its positin
 * @param parentId
 * @return the o based position of this title within is parent
 */
public int getTitlePositionUnderParent(int titleId, int parentId) {
    return (int) DatabaseUtils.longForQuery(getReadableDatabase(),
            SQL.SELECT + "count(*)" + SQL.FROM +
                    "(" + SQL.SELECT + " null " + SQL.FROM + BookDatabaseContract.TitlesEntry.TABLE_NAME +
                    SQL.WHERE +
                    BookDatabaseContract.TitlesEntry.COLUMN_NAME_PARENT_ID + "=? and " +
                    BookDatabaseContract.TitlesEntry.COLUMN_NAME_ID + "<? )",
            new String[]{String.valueOf(parentId), String.valueOf(titleId)});
}
 
Example #24
Source File: PreferenceIndexSqliteOpenHelper.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
private String buildLookupSQL(List<String> targetFragments) {
    StringBuilder stringBuilder = new StringBuilder(LOOKUP_SQL);
    for (String fragment : targetFragments) {
        DatabaseUtils.appendEscapedSQLString(stringBuilder, fragment);
        stringBuilder.append(",");
    }
    stringBuilder.setLength(stringBuilder.length() - 1); // Strip the last comma
    stringBuilder.append(")");
    return stringBuilder.toString();
}
 
Example #25
Source File: SqliteHelper.java    From tray with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to insert the values. If it fails because the item already exists it tries to update
 * the item.
 *
 * @param sqlDb                  database to work with. has to be writable
 * @param table                  the table to insert
 * @param selection              selection to detect a already inserted item
 * @param selectionArgs          keys of the contentValues. there values will be used as the
 *                               selectionArgs for the param selection
 * @param values                 the values to insert
 * @param excludeFieldsForUpdate contentValues keys which should be deleted before the update
 * @return 1 for insert, 0 for update and -1 if something goes wrong
 */
public static int insertOrUpdate(@Nullable SQLiteDatabase sqlDb, String table,
        @Nullable String selection, String[] selectionArgs, @NonNull final ContentValues values,
        @Nullable final String[] excludeFieldsForUpdate) {
    if (sqlDb == null) {
        return -1;
    }

    final long items = DatabaseUtils.queryNumEntries(sqlDb, table, selection, selectionArgs);

    if (items == 0) {
        // insert, item doesn't exist
        final long row = sqlDb.insert(table, null, values);
        if (row == -1) {
            // unknown error
            return -1;
        }
        // success, inserted
        return 1;
    } else {
        // update existing item

        if (excludeFieldsForUpdate != null) {
            for (String excludeField : excludeFieldsForUpdate) {
                values.remove(excludeField);
            }
        }

        sqlDb.update(table, values, selection, selectionArgs);

        // handling the update error is not needed. All possible errors are thrown by the
        // DatabaseUtils.queryNumEntries() (which uses the same params).
        // a wrong selection results only in an insert. update will never called then.
        return 0;
    }
}
 
Example #26
Source File: SettingsFragment.java    From android-notification-log with MIT License 5 votes vote down vote up
private void update() {
	try {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		long numRowsPosted = DatabaseUtils.queryNumEntries(db, DatabaseHelper.PostedEntry.TABLE_NAME);
		int stringResource = numRowsPosted == 1 ? R.string.settings_browse_summary_singular : R.string.settings_browse_summary_plural;
		prefBrowse.setSummary(getString(stringResource, numRowsPosted));
	} catch (Exception e) {
		if(Const.DEBUG) e.printStackTrace();
	}
}
 
Example #27
Source File: SQLiteLocationDAO.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
public long getLocationsForSyncCount(long millisSinceLastBatch) {
  String whereClause = TextUtils.join("", new String[]{
          SQLiteLocationContract.LocationEntry.COLUMN_NAME_STATUS + " = ? AND ( ",
          SQLiteLocationContract.LocationEntry.COLUMN_NAME_BATCH_START_MILLIS + " IS NULL OR ",
          SQLiteLocationContract.LocationEntry.COLUMN_NAME_BATCH_START_MILLIS + " < ? )",
  });
  String[] whereArgs = {
          String.valueOf(BackgroundLocation.SYNC_PENDING),
          String.valueOf(millisSinceLastBatch)
  };

  return DatabaseUtils.queryNumEntries(db, LocationEntry.TABLE_NAME, whereClause, whereArgs);
}
 
Example #28
Source File: MyStatusDBTask.java    From iBeebo with GNU General Public License v3.0 5 votes vote down vote up
public static void add(MessageListBean list, String accountId) {

        if (list == null || list.getSize() == 0) {
            return;
        }

        Gson gson = new Gson();
        List<MessageBean> msgList = list.getItemList();
        DatabaseUtils.InsertHelper ih = new DatabaseUtils.InsertHelper(getWsd(), MyStatusTable.StatusDataTable.TABLE_NAME);
        final int mblogidColumn = ih.getColumnIndex(MyStatusTable.StatusDataTable.MBLOGID);
        final int accountidColumn = ih.getColumnIndex(MyStatusTable.StatusDataTable.ACCOUNTID);
        final int jsondataColumn = ih.getColumnIndex(MyStatusTable.StatusDataTable.JSONDATA);
        try {
            getWsd().beginTransaction();
            for (int i = 0; i < msgList.size(); i++) {
                MessageBean msg = msgList.get(i);
                ih.prepareForInsert();
                if (msg != null) {
                    ih.bind(mblogidColumn, msg.getId());
                    ih.bind(accountidColumn, accountId);
                    String json = gson.toJson(msg);
                    ih.bind(jsondataColumn, json);
                } else {
                    ih.bind(mblogidColumn, "-1");
                    ih.bind(accountidColumn, accountId);
                    ih.bind(jsondataColumn, "");
                }
                ih.execute();
            }
            getWsd().setTransactionSuccessful();
        } catch (SQLException e) {
        } finally {
            getWsd().endTransaction();
            ih.close();
        }

    }
 
Example #29
Source File: MDSInterface2.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<Map<String, String>> getObservations(Context context, String uuid) {

        final String[] obsProjection = new String[]{
                Observations.Contract.UUID, Observations.Contract.ID,
                Observations.Contract.CONCEPT, Observations.Contract.VALUE,};
        List<Map<String, String>> observations = Collections.EMPTY_LIST;
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(
                    Observations.CONTENT_URI, obsProjection,
                    Observations.Contract.ENCOUNTER + " = ?",
                    new String[]{uuid}, Observations.Contract.ID + " ASC");
            observations = new ArrayList<Map<String, String>>(cursor.getCount());
            while (cursor.moveToNext()) {
                Map<String, String> obs = new HashMap<String, String>(4);
                // TODO handle complex observations
                obs.put(Observations.Contract.UUID, cursor.getString(0));
                obs.put(Observations.Contract.ID, cursor.getString(1));
                obs.put(Observations.Contract.CONCEPT, cursor.getString(2));
                obs.put(Observations.Contract.VALUE, cursor.getString(3));
                observations.add(obs);
                Log.d(TAG, DatabaseUtils.dumpCurrentRowToString(cursor));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return observations;
    }
 
Example #30
Source File: AccountsDb.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
long findAccountLastAuthenticatedTime(Account account) {
    SQLiteDatabase db = mDeDatabase.getReadableDatabase();
    return DatabaseUtils.longForQuery(db,
            "SELECT " + AccountsDb.ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
                    + " FROM " + TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
                    + ACCOUNTS_TYPE + "=?",
            new String[] {account.name, account.type});
}