Java Code Examples for android.database.Cursor#getBlob()

The following examples show how to use android.database.Cursor#getBlob() . 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: MessagingDatabase.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
protected List<ReactionRecord> parseReactions(@NonNull Cursor cursor) {
  byte[] raw = cursor.getBlob(cursor.getColumnIndexOrThrow(REACTIONS));

  if (raw != null) {
    try {
      return Stream.of(ReactionList.parseFrom(raw).getReactionsList())
                   .map(r -> {
                     return new ReactionRecord(r.getEmoji(),
                                               RecipientId.from(r.getAuthor()),
                                               r.getSentTime(),
                                               r.getReceivedTime());
                   })
                   .toList();
    } catch (InvalidProtocolBufferException e) {
      Log.w(TAG, "[parseReactions] Failed to parse reaction list!", e);
      return Collections.emptyList();
    }
  } else {
    return Collections.emptyList();
  }
}
 
Example 2
Source File: PrimitiveMethodsFactoryMethodStorIOSQLiteGetResolver.java    From storio with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@NonNull
public PrimitiveMethodsFactoryMethod mapFromCursor(@NonNull StorIOSQLite storIOSQLite, @NonNull Cursor cursor) {

    boolean field1 = cursor.getInt(cursor.getColumnIndex("field1")) == 1;
    short field2 = cursor.getShort(cursor.getColumnIndex("field2"));
    int field3 = cursor.getInt(cursor.getColumnIndex("field3"));
    long field4 = cursor.getLong(cursor.getColumnIndex("field4"));
    float field5 = cursor.getFloat(cursor.getColumnIndex("field5"));
    double field6 = cursor.getDouble(cursor.getColumnIndex("field6"));
    String field7 = cursor.getString(cursor.getColumnIndex("field7"));
    byte[] field8 = cursor.getBlob(cursor.getColumnIndex("field8"));

    PrimitiveMethodsFactoryMethod object = PrimitiveMethodsFactoryMethod.create(field1, field2, field3, field4, field5, field6, field7, field8);

    return object;
}
 
Example 3
Source File: SqlLiteStore.java    From PADListener with GNU General Public License v2.0 6 votes vote down vote up
private WebSocketMessageDTO buildChannelMessagesDTO(Cursor cs, WebSocketChannelDTO channel){
    WebSocketMessageDTO message = new WebSocketMessageDTO();
    message.id = cs.getInt(cs.getColumnIndex(SOCKET_MSG_ID));
    message.opcode = cs.getInt(cs.getColumnIndex(SOCKET_MSG_OPCODE));
    message.payloadLength = cs.getInt(cs.getColumnIndex(SOCKET_MSG_PAYLOAD_LENGTH));
    
    if (message.opcode == WebSocketMessage.OPCODE_TEXT){
        byte[] payloadAsString = cs.getBlob(cs.getColumnIndex(SOCKET_MSG_PAYLOAD_UTF8)); 
        message.payload = new String(payloadAsString);
    }else{
        message.payload = cs.getBlob(cs.getColumnIndex(SOCKET_MSG_PAYLOAD_BYTES)); 
    }
    message.isOutgoing = cs.getInt(cs.getColumnIndex(SOCKET_MSG_IS_OUTGOING)) == 1 ? true : false;
    message.timestamp = cs.getLong(cs.getColumnIndex(SOCKET_MSG_TIMESTAMP)); 
    message.readableOpcode = WebSocketMessage.opcode2string(message.opcode);
    message.channel = channel;
    return message;
}
 
Example 4
Source File: DaoImages.java    From geopaparazzi with GNU General Public License v3.0 6 votes vote down vote up
public byte[] getImageThumbnailById(SQLiteDatabase sqliteDatabase, long imageDataId) throws Exception {
    String[] asColumnsToReturn;
    String whereStr;
    asColumnsToReturn = new String[]{ //
            ImageDataTableFields.COLUMN_THUMBNAIL.getFieldName()//
    };
    whereStr = ImageDataTableFields.COLUMN_ID.getFieldName() + " = " + imageDataId;
    Cursor c = sqliteDatabase.query(TABLE_IMAGE_DATA, asColumnsToReturn, whereStr, null, null, null, null);
    byte[] imageData = null;
    try {
        c.moveToFirst();
        imageData = null;
        if (!c.isAfterLast()) {
            imageData = c.getBlob(0);
        }
    } finally {
        c.close();
    }
    return imageData;
}
 
Example 5
Source File: PrimitiveFieldsStorIOContentResolverGetResolver.java    From storio with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@NonNull
public PrimitiveFields mapFromCursor(@NonNull StorIOContentResolver storIOContentResolver, @NonNull Cursor cursor) {
    PrimitiveFields object = new PrimitiveFields();

    object.field1 = cursor.getInt(cursor.getColumnIndex("field1")) == 1;
    object.field2 = cursor.getShort(cursor.getColumnIndex("field2"));
    object.field3 = cursor.getInt(cursor.getColumnIndex("field3"));
    object.field4 = cursor.getLong(cursor.getColumnIndex("field4"));
    object.field5 = cursor.getFloat(cursor.getColumnIndex("field5"));
    object.field6 = cursor.getDouble(cursor.getColumnIndex("field6"));
    object.field7 = cursor.getString(cursor.getColumnIndex("field7"));
    object.field8 = cursor.getBlob(cursor.getColumnIndex("field8"));

    return object;
}
 
Example 6
Source File: SyncStateContract.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public static Pair<Uri, byte[]> getWithUri(ContentProviderClient provider, Uri uri,
        Account account) throws RemoteException {
    Cursor c = provider.query(uri, DATA_PROJECTION, SELECT_BY_ACCOUNT,
            new String[]{account.name, account.type}, null);

    if (c == null) {
        throw new RemoteException();
    }

    try {
        if (c.moveToNext()) {
            long rowId = c.getLong(1);
            byte[] blob = c.getBlob(c.getColumnIndexOrThrow(Columns.DATA));
            return Pair.create(ContentUris.withAppendedId(uri, rowId), blob);
        }
    } finally {
        c.close();
    }
    return null;
}
 
Example 7
Source File: PrimitivePrivateFieldsStorIOSQLiteGetResolver.java    From storio with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@NonNull
public PrimitivePrivateFields mapFromCursor(@NonNull StorIOSQLite storIOSQLite, @NonNull Cursor cursor) {

    boolean field1 = cursor.getInt(cursor.getColumnIndex("field1")) == 1;
    short field2 = cursor.getShort(cursor.getColumnIndex("field2"));
    int field3 = cursor.getInt(cursor.getColumnIndex("field3"));
    long field4 = cursor.getLong(cursor.getColumnIndex("field4"));
    float field5 = cursor.getFloat(cursor.getColumnIndex("field5"));
    double field6 = cursor.getDouble(cursor.getColumnIndex("field6"));
    String field7 = cursor.getString(cursor.getColumnIndex("field7"));
    byte[] field8 = cursor.getBlob(cursor.getColumnIndex("field8"));

    PrimitivePrivateFields object = new PrimitivePrivateFields(field1, field2, field3, field4, field5, field6, field7, field8);

    return object;
}
 
Example 8
Source File: MeshNetworkDb.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void migrateGroup(final SupportSQLiteDatabase database) {
    database.execSQL("CREATE TABLE `groups_temp` " +
            "(`id` INTEGER PRIMARY KEY NOT NULL," +
            "`mesh_uuid` TEXT, " +
            "`name` TEXT, " +
            "`group_address` INTEGER NOT NULL DEFAULT 49152, " +
            "`parent_address` INTEGER NOT NULL DEFAULT 49152, " +
            "FOREIGN KEY(`mesh_uuid`) REFERENCES `mesh_network`(`mesh_uuid`) ON UPDATE CASCADE ON DELETE CASCADE )");

    final Cursor cursor = database.query("SELECT * FROM groups");
    if (cursor != null && cursor.moveToFirst()) {
        do {
            final String uuid = cursor.getString(cursor.getColumnIndex("mesh_uuid"));
            final String name = cursor.getString(cursor.getColumnIndex("name"));
            final byte[] grpAddress = cursor.getBlob(cursor.getColumnIndex("group_address"));
            final byte[] pAddress = cursor.getBlob(cursor.getColumnIndex("parent_address"));
            final int groupAddress = MeshParserUtils.unsignedBytesToInt(grpAddress[1], grpAddress[0]);
            final ContentValues values = new ContentValues();
            values.put("mesh_uuid", uuid);
            values.put("name", name);
            values.put("group_address", groupAddress);
            if (pAddress != null) {
                final int parentAddress = MeshParserUtils.unsignedBytesToInt(pAddress[1], pAddress[0]);
                values.put("parent_address", parentAddress);
            }
            database.insert("groups_temp", SQLiteDatabase.CONFLICT_REPLACE, values);
        } while (cursor.moveToNext());
        cursor.close();
    }

    database.execSQL("DROP TABLE groups");
    database.execSQL("ALTER TABLE groups_temp RENAME TO groups");
    database.execSQL("CREATE INDEX index_groups_mesh_uuid ON `groups` (mesh_uuid)");
}
 
Example 9
Source File: PasswordDatabase.java    From Password-Storage with MIT License 5 votes vote down vote up
public Bitmap getPic(){
    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cursor = db.query(PHOTO_TABLE, new String[]{COLUMN_PHOTO}, null, null,null,null,null);
    byte[] image = new byte[]{};
    if (cursor.moveToFirst()) {
        do {
            image= cursor.getBlob(0);
        } while (cursor.moveToNext());
    }

    cursor.close();
    db.close();
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}
 
Example 10
Source File: HistoricalData.java    From SweetBlue with GNU General Public License v3.0 5 votes vote down vote up
public static @Nullable(Nullable.Prevalence.NEVER) HistoricalData fromCursor(final Cursor cursor)
{
	if( cursor == null )
	{
		return HistoricalData.NULL;
	}

	final HistoricalData data = new HistoricalData(cursor.getLong(HistoricalDataColumn.EPOCH_TIME.getColumnIndex()), cursor.getBlob(HistoricalDataColumn.DATA.getColumnIndex()));

	return data;
}
 
Example 11
Source File: ChatSettingsDao.java    From Yahala-Messenger with MIT License 5 votes vote down vote up
/**
 * @inheritdoc
 */
@Override
public ChatSettings readEntity(Cursor cursor, int offset) {
    ChatSettings entity = new ChatSettings( //
            cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0), // jid
            cursor.isNull(offset + 1) ? null : cursor.getBlob(offset + 1) // participants
    );
    return entity;
}
 
Example 12
Source File: DBPlace.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
public List<Place> toList(Cursor cursor) {

        List<Place> list = new ArrayList<Place>();

        try {
            int count = cursor.getCount();
            cursor.moveToFirst();
            for (int i = 0; i < count; i++) {
                String code = cursor.getString(cursor
                        .getColumnIndex(DBPlace.FIELD_CODE));
                String pcode = cursor.getString(cursor
                        .getColumnIndex(DBPlace.FIELD_PCODE));
                byte[] bytes = cursor.getBlob(cursor
                        .getColumnIndex(DBPlace.FIELD_NAME));
                int level = cursor.getInt(cursor
                        .getColumnIndex(DBPlace.FIELD_LEVEL));
                String name = new String(bytes, "utf-8");

                Place myListItem = new Place();

                myListItem.setName(name);
                myListItem.setCode(code);
                myListItem.setPcode(pcode);
                myListItem.setLevel(level);

                list.add(myListItem);
                cursor.moveToNext();
            }

        } catch (Exception e) {
            ZogUtils.showException(e);
        }
//        LogUtils.printLog(getClass(), "list.size():" + list.size());
        return list;
    }
 
Example 13
Source File: ZrtpCacheDB.java    From zrtp-java with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ZrtpCacheEntry get(String zid) {
	ZrtpCacheEntry entry = null;
	
	String zidDbFormat = convertToDBFormat(zid);

	String[] zidColumn = new String[] { COLUMN_ZID,
			COLUMN_DATA,
			COLUMN_NUMBER};

	Cursor cursor = this.database.query(TABLE_NAME, zidColumn, COLUMN_ZID + "='" + zidDbFormat + "'", null,
			null, null, null);
	
	logger.log("[Zrtp Cache] Found " + cursor.getCount() + " entry in zrtp_cache_db for zid " + zidDbFormat);

	if (cursor.moveToFirst()) {
		do {
			entry = new AndroidCacheEntry(convertFromDBFormat(cursor.getString(0)),
					cursor.getBlob(1),
					cursor.getString(2));
		} while (cursor.moveToNext());
	}
	if (cursor != null && !cursor.isClosed()) {
		cursor.close();
	}
	
	if (entry != null) {
		logger.log("[Zrtp Cache] Entry for "  + zidDbFormat + " and number " + entry.getNumber() + " found!");
	} else
		logger.log("[Zrtp Cache] No entry found!");
	
	return entry;
}
 
Example 14
Source File: RNUnifiedContactsModule.java    From react-native-unified-contacts with MIT License 5 votes vote down vote up
@NonNull
private WritableMap getThumbnailFromContact(int contactId) {
    WritableMap thumbnail = Arguments.createMap();

    // NOTE: See this for getting the high-res image: https://developer.android.com/reference/android/provider/ContactsContract.Contacts.Photo.html

    Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
    Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

    Cursor photoCursor = contentResolver.query(
        photoUri,
        new String[] {ContactsContract.Contacts.Photo.PHOTO},
        null,
        null,
        null,
        null);

    if ( !photoCursor.moveToFirst() ) return thumbnail;

    byte[] data = photoCursor.getBlob(0);

    if (data != null) {
        thumbnail.putBoolean( "imageDataAvailable", true );

        String base64Thumbnail = Base64.encodeToString(data, Base64.DEFAULT);

        thumbnail.putString( "thumbnailImageData", base64Thumbnail );
    }
    else {
        thumbnail.putBoolean( "imageDataAvailable", false );
    }

    photoCursor.close();

    return thumbnail;
}
 
Example 15
Source File: SqlLiteStore.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
private Map<String, DNSResponseDto> buildDnsResponseDTOs(Cursor cs){
    Map<String, DNSResponseDto> responses = new HashMap<String, DNSResponseDto>();
    while (cs.moveToNext()) {
        String request = cs.getString(cs.getColumnIndex(DNS_RESPONSE_REQUEST));
        long timestamp = cs.getLong(cs.getColumnIndex(DNS_RESPONSE_TS));
        byte[] responseBlob = cs.getBlob(cs.getColumnIndex(DNS_RESPONSE_RESPONSE_BLOB));
        String providerId = cs.getString(cs.getColumnIndex(DNS_RESPONSE_PROVIDER_ID));
        int reqTimes = cs.getInt(cs.getColumnIndex(DNS_RESPONSE_REQUESTS_NR));
        DNSResponseDto response = new DNSResponseDto(request, timestamp, providerId, responseBlob, reqTimes);
        response.setDNSResponse(responseBlob);
        responses.put(request, response);
    }
    return responses;
}
 
Example 16
Source File: PluginDatabaseManager.java    From PluginLoader with Apache License 2.0 4 votes vote down vote up
/**
 * convert to info list
 *
 * @param cursor cursor
 * @return infos
 */
private PluginDescriptor convertToPlugin(Cursor cursor) {
	if (cursor == null || cursor.getCount() == 0) {
		return null;
	} else {
		PluginDescriptor pluginDescriptor = new PluginDescriptor();
		String pluginId = cursor.getString(cursor.getColumnIndex(Columns.PLUGIN_ID));
		String url = cursor.getString(cursor.getColumnIndex(Columns.URL));
		String pluginName = cursor.getString(cursor.getColumnIndex(Columns.PLUGIN_NAME));
		String packageName = cursor.getString(cursor.getColumnIndex(Columns.PACKAGE_NAME));
		String path = cursor.getString(cursor.getColumnIndex(Columns.INSTALL_PATH));
		String version = cursor.getString(cursor.getColumnIndex(Columns.VERSION));
		String mianAt = cursor.getString(cursor.getColumnIndex(Columns.APK_MAINACTIVITY));
		int status = cursor.getInt(cursor.getColumnIndex(Columns.STATUS));
		int type = cursor.getInt(cursor.getColumnIndex(Columns.TYPE));
		String descripion = cursor.getString(cursor.getColumnIndex(Columns.DESCRIPTION));
		int isEnableValue = cursor.getInt(cursor.getColumnIndex(Columns.IS_ENABLED));
		int isStandaloneValue = cursor.getInt(cursor.getColumnIndex(Columns.IS_STANDALONE));
		byte[] appIconByte = cursor.getBlob(cursor.getColumnIndex(Columns.APP_ICON));
		String applicationName = cursor.getString(cursor.getColumnIndex(Columns.APPLICATION_NAME));
		int applicationLogo = cursor.getInt(cursor.getColumnIndex(Columns.APPLICATION_LOGO));
		int apiacationIcon = cursor.getInt(cursor.getColumnIndex(Columns.APPLICATION_ICON));
		int applicationTheme = cursor.getInt(cursor.getColumnIndex(Columns.APPLICATION_THEME));
		String activityInfos = cursor.getString(cursor.getColumnIndex(Columns.ACTIVITY_INFOS));
		String providerInfos = cursor.getString(cursor.getColumnIndex(Columns.PROVIDER_INFOS));
		String activitys = cursor.getString(cursor.getColumnIndex(Columns.ACTIVITYS));
		String fragments = cursor.getString(cursor.getColumnIndex(Columns.FRAGMENTS));
		String services = cursor.getString(cursor.getColumnIndex(Columns.SERVICES));
		String receivers = cursor.getString(cursor.getColumnIndex(Columns.RECEIVERS));
		String mata = cursor.getString(cursor.getColumnIndex(Columns.METADATA));
		String progressMap = cursor.getString(cursor.getColumnIndex(Columns.PROGRESS_MAP));

		// constucts pluginModel
		pluginDescriptor.setPluginID(pluginId);
		pluginDescriptor.setPackageName(packageName);
		pluginDescriptor.setPluginName(pluginName);
		pluginDescriptor.setApkMainActivity(mianAt);
		pluginDescriptor.setVersion(version);
		pluginDescriptor.setPluginType(type);
		pluginDescriptor.setUrl(url);
		pluginDescriptor.setInstalledPath(path);
		pluginDescriptor.setStatus(status);
		pluginDescriptor.setApkMainActivity(mianAt);
		pluginDescriptor.setDescription(descripion);
		pluginDescriptor.setApplicationIcon(apiacationIcon);
		pluginDescriptor.setApplicationName(applicationName);
		pluginDescriptor.setApplicationTheme(applicationTheme);
		pluginDescriptor.setApplicationLogo(applicationLogo);
		pluginDescriptor.setEnabled(isEnableValue == 0);
		pluginDescriptor.setStandalone(isStandaloneValue == 0);
		pluginDescriptor.setAppIcon(appIconByte);
		pluginDescriptor.setActivityInfos(
				JsonUtil.parseObject(activityInfos, new TypeReference<HashMap<String, PluginActivityInfo>>() {
				}));
		pluginDescriptor.setActivitys(
				JsonUtil.parseObject(activitys, new TypeReference<HashMap<String, ArrayList<PluginIntentFilter>>>() {
				}));
		pluginDescriptor.setProviderInfos(
				JsonUtil.parseObject(providerInfos, new TypeReference<HashMap<String, PluginProviderInfo>>() {
				}));
		pluginDescriptor.setfragments(
				JsonUtil.parseObject(fragments, new TypeReference<HashMap<String, String>>() {
				}));
		pluginDescriptor.setReceivers(
				JsonUtil.parseObject(receivers, new TypeReference<HashMap<String, ArrayList<PluginIntentFilter>>>() {

				}));
		pluginDescriptor.setServices(
				JsonUtil.parseObject(services, new TypeReference<HashMap <String, ArrayList< PluginIntentFilter >>>(){

				}));
		pluginDescriptor.setMetaData(
				JsonUtil.parseObject(mata, new TypeReference<HashMap<String, String>>(){ }));
		return pluginDescriptor;
	}
}
 
Example 17
Source File: Storage.java    From beacons-android with Apache License 2.0 4 votes vote down vote up
public static Beacon fromCursor(Cursor cursor) {
    Beacon beacon;
    int kind = cursor.getInt(12);

    switch (kind) {
        case KIND_EDDYSTONE_URL:
            beacon = new EddystoneURL(cursor.getString(1),
                    cursor.isNull(0) ? null : cursor.getBlob(0));
            break;
        case KIND_EDDYSTONE_UID:
            beacon = new EddystoneUID(cursor.getBlob(1), cursor.getString(2),
                    cursor.isNull(0) ? null : cursor.getBlob(0), null);
            break;
        case KIND_EDDYSTONE_EID:
            beacon = new EddystoneEID(cursor.getBlob(1), (byte) cursor.getInt(2), cursor.getInt(3),
                    cursor.isNull(0) ? null : cursor.getBlob(0));
            break;
        case KIND_EDDYSTONE_TLM:
            beacon = new EddystoneTLM(cursor.getInt(1), cursor.isNull(0) ? null : cursor.getBlob(0));
            break;
        case KIND_IBEACON:
            beacon = new iBeacon(cursor.getBlob(0), cursor.getInt(1), cursor.getInt(2));
            break;
        default:
            Persistable persistable = null == getInstance().mBeaconPersisters ? null : getInstance().mBeaconPersisters.get(kind);
            beacon = null == persistable ? null : persistable.fromCursor(cursor);
            break;
    }

    if (null != beacon) {
        long itemId = cursor.getLong(7);
        @Advertiser.Mode int advertiseMode = cursor.getInt(9);
        @Advertiser.Power int txPowerLevel = cursor.getInt(10);
        int flags = cursor.getInt(11);
        String name = cursor.getString(13);

        beacon.init(itemId, advertiseMode, txPowerLevel, flags, name);
        beacon.setActiveState(cursor.getInt(8));
    }

    return beacon;
}
 
Example 18
Source File: MeshNetworkDb.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static void migrateNodes(final SupportSQLiteDatabase database) {
    database.execSQL("CREATE TABLE `nodes_temp` " +
            "(`timestamp` INTEGER NOT NULL, " +
            "`mAddedNetworkKeys` TEXT, " +
            "`name` TEXT, `ttl` INTEGER, " +
            "`blacklisted` INTEGER NOT NULL, " +
            "`secureNetworkBeacon` INTEGER, " +
            "`mesh_uuid` TEXT, `uuid` TEXT NOT NULL, " +
            "`security` INTEGER NOT NULL, " +
            "`unicast_address` INTEGER NOT NULL DEFAULT 1, " +
            "`configured` INTEGER NOT NULL, " +
            "`device_key` BLOB, " +
            "`seq_number` INTEGER NOT NULL, " +
            "`cid` INTEGER, " +
            "`pid` INTEGER, " +
            "`vid` INTEGER, " +
            "`crpl` INTEGER, " +
            "`mElements` TEXT, " +
            "`mAddedApplicationKeys` TEXT, " +
            "`networkTransmitCount` INTEGER, " +
            "`networkIntervalSteps` INTEGER, " +
            "`relayTransmitCount` INTEGER, " +
            "`relayIntervalSteps` INTEGER, " +
            "`friend` INTEGER, " +
            "`lowPower` INTEGER, " +
            "`proxy` INTEGER, " +
            "`relay` INTEGER, " +
            "PRIMARY KEY(`uuid`), " +
            "FOREIGN KEY(`mesh_uuid`) REFERENCES `mesh_network`(`mesh_uuid`) ON UPDATE CASCADE ON DELETE CASCADE )");

    database.execSQL(
            "INSERT INTO nodes_temp (timestamp, mAddedNetworkKeys, name, blacklisted, secureNetworkBeacon, mesh_uuid, " +
                    "security, configured, device_key, seq_number, cid, pid, vid, crpl, mElements, " +
                    "mAddedApplicationKeys, networkTransmitCount, networkIntervalSteps, relayTransmitCount, relayIntervalSteps, " +
                    "friend, lowPower, proxy, relay, uuid, mesh_uuid) " +
                    "SELECT timestamp, mAddedNetworkKeys, name, blacklisted, secureNetworkBeacon, mesh_uuid, " +
                    "security, configured, device_key, seq_number, cid, pid, vid, crpl, mElements, " +
                    "mAddedApplicationKeys, networkTransmitCount, networkIntervalSteps, relayTransmitCount, relayIntervalSteps," +
                    "friend, lowPower, proxy, relay, uuid, mesh_uuid FROM nodes");

    final Cursor cursor = database.query("SELECT * FROM nodes");
    if (cursor != null && cursor.moveToFirst()) {
        do {
            final String uuid = cursor.getString(cursor.getColumnIndex("uuid"));
            final byte[] unicast = cursor.getBlob(cursor.getColumnIndex("unicast_address"));
            final int address = MeshAddress.addressBytesToInt(unicast);
            final ContentValues values = new ContentValues();
            values.put("unicast_address", address);
            database.update("nodes_temp", SQLiteDatabase.CONFLICT_REPLACE, values, "uuid = ?", new String[]{uuid});
        } while (cursor.moveToNext());
        cursor.close();
    }
    database.execSQL("DROP TABLE nodes");
    database.execSQL("ALTER TABLE nodes_temp RENAME TO nodes");
    database.execSQL("CREATE INDEX index_nodes_mesh_uuid ON `nodes` (mesh_uuid)");
}
 
Example 19
Source File: DatabaseCursorTest.java    From sqlite-android with Apache License 2.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@MediumTest
@Test
public void testBlob() {
    // create table
    mDatabase.execSQL(
        "CREATE TABLE test (_id INTEGER PRIMARY KEY, s TEXT, d REAL, l INTEGER, b BLOB);");
    // insert blob
    Object[] args = new Object[4];
    
    byte[] blob = new byte[1000];
    byte value = 99;
    Arrays.fill(blob, value);        
    args[3] = blob;
    
    String s = "text";
    args[0] = s;
    Double d = 99.9;
    args[1] = d;
    Long l = (long)1000;
    args[2] = l;
    
    String sql = "INSERT INTO test (s, d, l, b) VALUES (?,?,?,?)";
    mDatabase.execSQL(sql, args);
    // use cursor to access blob
    Cursor c = mDatabase.query("test", null, null, null, null, null, null);        
    c.moveToNext();
    ContentValues cv = new ContentValues();
    //DatabaseUtils.cursorRowToContentValues(c, cv);
    String[] columns = c.getColumnNames();
    int length = columns.length;
    for (int i = 0; i < length; i++) {
        if (c.getType(i) == Cursor.FIELD_TYPE_BLOB) {
            cv.put(columns[i], c.getBlob(i));
        } else {
            cv.put(columns[i], c.getString(i));
        }
    }
    
    int bCol = c.getColumnIndexOrThrow("b");
    int sCol = c.getColumnIndexOrThrow("s");
    int dCol = c.getColumnIndexOrThrow("d");
    int lCol = c.getColumnIndexOrThrow("l");
    byte[] cBlob =  c.getBlob(bCol);
    assertTrue(Arrays.equals(blob, cBlob));
    assertEquals(s, c.getString(sCol));
    assertEquals(d, new Double(c.getDouble(dCol)));
    assertEquals((long)l, c.getLong(lCol));
    c.close();
}
 
Example 20
Source File: SQLiteUtils.java    From tedroid with Apache License 2.0 2 votes vote down vote up
/**
 * @param cursor un objeto Cursor.
 * @param columnName el nombre de la columna.
 * @return el valor de la columna. Si no existe la columna o el valor de la columna es
 *         {@code null} entonces {@code null}.
 */
static byte[] getBlob(Cursor cursor, String columnName) {
    return containsColumn(cursor, columnName) && !cursor.isNull(cursor.getColumnIndex(columnName))
            ? cursor.getBlob(cursor.getColumnIndex(columnName))
            : null;
}