Java Code Examples for android.os.Parcel.setDataPosition()

The following are Jave code examples for showing how to use setDataPosition() of the android.os.Parcel class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Udacity_Sunshine   File: ItemChoiceManager.java   View Source Code Vote up 7 votes
public void onRestoreInstanceState(Bundle savedInstanceState) {
    byte[] states = savedInstanceState.getByteArray(SELECTED_ITEMS_KEY);
    if ( null != states ) {
        Parcel inParcel = Parcel.obtain();
        inParcel.unmarshall(states, 0, states.length);
        inParcel.setDataPosition(0);
        mCheckStates = inParcel.readSparseBooleanArray();
        final int numStates = inParcel.readInt();
        mCheckedIdStates.clear();
        for (int i=0; i<numStates; i++) {
            final long key = inParcel.readLong();
            final int value = inParcel.readInt();
            mCheckedIdStates.put(key, value);
        }
    }
}
 
Example 2
Project: nifi-android-s2s   File: SerializationUtils.java   View Source Code Vote up 6 votes
/**
 * Unmarshalls a serializable's byte array into the object
 *
 * @param bytes the bytes
 * @param <T>   the type
 * @return the object
 */
@SuppressWarnings("unchecked")
public static <T extends Serializable> T unmarshallSerializable(byte[] bytes) {
    if (bytes == null) {
        return null;
    }
    Parcel parcel = Parcel.obtain();
    parcel.unmarshall(bytes, 0, bytes.length);
    parcel.setDataPosition(0);

    try {
        return (T) parcel.readSerializable();
    } catch (Exception e) {
        throw new BadParcelableException(e);
    } finally {
        parcel.recycle();
    }
}
 
Example 3
Project: OpenYOLO-Android   File: CredentialRetrieveRequestTest.java   View Source Code Vote up 6 votes
@Test
public void testWriteAndRead() {
    CredentialRetrieveRequest request = new CredentialRetrieveRequest.Builder(
            AuthenticationMethods.EMAIL)
            .setTokenProviders(ValidTokenProviderMap.make())
            .setAdditionalProperties(ValidAdditionalProperties.make())
            .setRequireUserMediation(true)
            .build();

    Parcel p = Parcel.obtain();
    try {
        request.writeToParcel(p, 0);
        p.setDataPosition(0);
        CredentialRetrieveRequest deserialized = CredentialRetrieveRequest.CREATOR.createFromParcel(p);
        assertThat(deserialized).isNotNull();
        assertThat(deserialized.getAuthenticationMethods())
                .isEqualTo(request.getAuthenticationMethods());
        ValidTokenProviderMap.assertEquals(deserialized.getTokenProviders());
        ValidAdditionalProperties.assertEquals(deserialized.getAdditionalProperties());
        assertThat(deserialized.getRequireUserMediation()).isTrue();
    } finally {
        p.recycle();
    }
}
 
Example 4
Project: Phoenix-for-VK   File: BundleUtil.java   View Source Code Vote up 6 votes
public static Bundle deserializeBundle(final String base64) {
    Bundle bundle;

    final Parcel parcel = Parcel.obtain();
    try {
        final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        final byte[] buffer = new byte[1024];
        final GZIPInputStream zis = new GZIPInputStream(new ByteArrayInputStream(Base64.decode(base64, 0)));
        int len;
        while ((len = zis.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        zis.close();
        parcel.unmarshall(byteBuffer.toByteArray(), 0, byteBuffer.size());
        parcel.setDataPosition(0);
        bundle = parcel.readBundle();
    } catch (IOException e) {
        e.printStackTrace();
        bundle = null;
    } finally {
        parcel.recycle();
    }

    return bundle;
}
 
Example 5
Project: Hexis   File: QuadrantItemTest.java   View Source Code Vote up 6 votes
@Test
public void createFromParcel() throws Exception {
  String msg = "TEST";

  // Create a new item with the msg String
  QuadrantItem item = new QuadrantItem(msg);

  // Obtain a Parcel
  Parcel src = Parcel.obtain();

  // Save the item to a Parcel
  item.writeToParcel(src, 0);

  // Reset data position
  src.setDataPosition(0);

  // Create a new item from the saved Parcel
  QuadrantItem test = QuadrantItem.CREATOR.createFromParcel(src);

  // Assert that the messages are equal
  assertEquals(msg, test.getMessage());
}
 
Example 6
Project: JobSchedulerCompat   File: PersistableBundleTest.java   View Source Code Vote up 6 votes
@Test
public void testParcelling() {
    PersistableBundle bundle = new PersistableBundle();
    bundle.putString("string", "string");
    bundle.putInt("int", 0);
    bundle.putLong("long", 0);
    bundle.putBoolean("boolean", true);
    // Can't use double or any array, as the instances would be different and equals() would fail.
    Parcel parcel = Parcel.obtain();
    parcel.writeValue(bundle);
    byte[] bytes = parcel.marshall();
    parcel.recycle();
    parcel = Parcel.obtain();
    parcel.unmarshall(bytes, 0, bytes.length);
    parcel.setDataPosition(0);
    PersistableBundle parcelledBundle =
            (PersistableBundle) parcel.readValue(PersistableBundle.class.getClassLoader());

    assertEquals(bundle.toMap(1), parcelledBundle.toMap(1));
}
 
Example 7
Project: q-mail   File: SMimeMetadata.java   View Source Code Vote up 6 votes
public void writeToParcel(Parcel dest, int flags) {
    /**
     * NOTE: When adding fields in the process of updating this API, make sure to bump
     * {@link #PARCELABLE_VERSION}.
     */
    dest.writeInt(PARCELABLE_VERSION);
    // Inject a placeholder that will store the parcel size from this point on
    // (not including the size itself).
    int sizePosition = dest.dataPosition();
    dest.writeInt(0);
    int startPosition = dest.dataPosition();
    // version 1
    dest.writeString(filename);
    dest.writeString(mimeType);
    dest.writeLong(modificationTime);
    dest.writeLong(originalSize);
    // version 2
    dest.writeString(charset);
    // Go back and write the size
    int parcelableSize = dest.dataPosition() - startPosition;
    dest.setDataPosition(sizePosition);
    dest.writeInt(parcelableSize);
    dest.setDataPosition(startPosition + parcelableSize);
}
 
Example 8
Project: Cable-Android   File: MasterSecret.java   View Source Code Vote up 6 votes
public MasterSecret parcelClone() {
  Parcel thisParcel = Parcel.obtain();
  Parcel thatParcel = Parcel.obtain();
  byte[] bytes      = null;

  thisParcel.writeValue(this);
  bytes = thisParcel.marshall();

  thatParcel.unmarshall(bytes, 0, bytes.length);
  thatParcel.setDataPosition(0);

  MasterSecret that = (MasterSecret)thatParcel.readValue(MasterSecret.class.getClassLoader());

  thisParcel.recycle();
  thatParcel.recycle();

  return that;
}
 
Example 9
Project: nifi-android-s2s   File: DemoAppDB.java   View Source Code Vote up 6 votes
/**
 * Saves the repeatable intent (useful for later cancelling an alarm after the application has restarted)
 *
 * @param siteToSiteRepeatableIntent the repeatable intent
 */
public void save(SiteToSiteRepeatableIntent siteToSiteRepeatableIntent) {
    Parcel parcel = Parcel.obtain();
    siteToSiteRepeatableIntent.getIntent().writeToParcel(parcel, 0);
    parcel.setDataPosition(0);
    byte[] bytes = parcel.marshall();
    SQLiteDatabase writableDatabase = sqLiteOpenHelper.getWritableDatabase();
    try {
        ContentValues contentValues = new ContentValues();
        contentValues.put(PENDING_INTENT_REQUEST_CODE, siteToSiteRepeatableIntent.getRequestCode());
        contentValues.put(CONTENT_COLUMN, bytes);
        writableDatabase.insertOrThrow(PENDING_INTENT_TABLE_NAME, null, contentValues);
    } finally {
        writableDatabase.close();
    }
}
 
Example 10
Project: OpenYOLO-Android   File: ActivityResultTest.java   View Source Code Vote up 6 votes
@Test
public void parcelAndUnparcel_withValidInput_returnsEquivalent() throws Exception {
    Parcel parcel = Parcel.obtain();

    int resultCode = CredentialDeleteResult.CODE_BAD_REQUEST;
    Intent intent = CredentialDeleteResult.BAD_REQUEST.toResultDataIntent();

    // Act
    ActivityResult givenActivityResult = ActivityResult.of(resultCode, intent);
    givenActivityResult.writeToParcel(parcel, 0 /* flags */);

    parcel.setDataPosition(0);
    ActivityResult outputActivityResult = ActivityResult.CREATOR.createFromParcel(parcel);

    // Assert
    assertThat(outputActivityResult.getResultCode()).isEqualTo(resultCode);

    CredentialDeleteResult credentialDeleteResult =
            CredentialDeleteResult.fromResultIntentData(outputActivityResult.getData());
    assertThat(credentialDeleteResult.getResultCode()).isEqualTo(resultCode);
}
 
Example 11
Project: TPlayer   File: PackageParserEx.java   View Source Code Vote up 6 votes
public static void readSignature(VPackage pkg) {
    File signatureFile = VEnvironment.getSignatureFile(pkg.packageName);
    if (!signatureFile.exists()) {
        return;
    }
    Parcel p = Parcel.obtain();
    try {
        FileInputStream fis = new FileInputStream(signatureFile);
        byte[] bytes = FileUtils.toByteArray(fis);
        fis.close();
        p.unmarshall(bytes, 0, bytes.length);
        p.setDataPosition(0);
        pkg.mSignatures = p.createTypedArray(Signature.CREATOR);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        p.recycle();
    }
}
 
Example 12
Project: VirtualHook   File: PendingIntentData.java   View Source Code Vote up 5 votes
public static PendingIntent readPendingIntent(IBinder binder) {
    Parcel parcel = Parcel.obtain();
    parcel.writeStrongBinder(binder);
    parcel.setDataPosition(0);
    try {
        return PendingIntent.readPendingIntentOrNullFromParcel(parcel);
    } finally {
        parcel.recycle();
    }
}
 
Example 13
Project: OpenYOLO-Android   File: QueryResponseTest.java   View Source Code Vote up 5 votes
@Test
public void testWriteAndReadParcel_noResponseMessage() {
    QueryResponse queryResponse = new QueryResponse(PACKAGE, RESPONSE_ID, null);
    Parcel p = Parcel.obtain();
    p.writeParcelable(queryResponse, 0);
    p.setDataPosition(0);
    QueryResponse read = p.readParcelable(QueryResponse.class.getClassLoader());

    assertThat(read.responderPackage).isEqualTo(QUERY_RESPONSE.responderPackage);
    assertThat(read.responseId).isEqualTo(QUERY_RESPONSE.responseId);
    assertThat(read.responseMessage).isNull();
}
 
Example 14
Project: aos-MediaLib   File: MediaMetadata.java   View Source Code Vote up 5 votes
public MediaMetadata createFromParcel(Parcel p) {
    MediaMetadata metadata = new MediaMetadata();
    Parcel data = Parcel.obtain();

    data.appendFrom(p, p.dataPosition(), p.dataAvail());
    data.setDataPosition(0);
    if (metadata.parse(data))
        return metadata;
    else
        return null;
}
 
Example 15
Project: RLibrary   File: CacheUtils.java   View Source Code Vote up 5 votes
private static <T> T bytes2Parcelable(byte[] bytes, Parcelable.Creator<T> creator) {
    if (bytes == null) return null;
    Parcel parcel = Parcel.obtain();
    parcel.unmarshall(bytes, 0, bytes.length);
    parcel.setDataPosition(0);
    T result = creator.createFromParcel(parcel);
    parcel.recycle();
    return result;
}
 
Example 16
Project: Cable-Android   File: ParcelUtil.java   View Source Code Vote up 4 votes
public static Parcel deserialize(byte[] bytes) {
  Parcel parcel = Parcel.obtain();
  parcel.unmarshall(bytes, 0, bytes.length);
  parcel.setDataPosition(0);
  return parcel;
}
 
Example 17
Project: TPlayer   File: VAccountManagerService.java   View Source Code Vote up 4 votes
/**
 * Read all accounts from file.
 */
private void readAllAccounts() {
    File accountFile = VEnvironment.getAccountConfigFile();
    refreshAuthenticatorCache(null);
    if (accountFile.exists()) {
        accountsByUserId.clear();
        Parcel dest = Parcel.obtain();
        try {
            FileInputStream is = new FileInputStream(accountFile);
            byte[] bytes = new byte[(int) accountFile.length()];
            int readLength = is.read(bytes);
            is.close();
            if (readLength != bytes.length) {
                throw new IOException(String.format(Locale.ENGLISH, "Expect length %d, but got %d.", bytes.length, readLength));
            }
            dest.unmarshall(bytes, 0, bytes.length);
            dest.setDataPosition(0);
            dest.readInt(); // skip the magic
            int size = dest.readInt(); // the VAccount's size we need to read
            boolean invalid = false;
            while (size-- > 0) {
                VAccount account = new VAccount(dest);
                VLog.d(TAG, "Reading account : " + account.type);
                AuthenticatorInfo info = cache.authenticators.get(account.type);
                if (info != null) {
                    List<VAccount> accounts = accountsByUserId.get(account.userId);
                    if (accounts == null) {
                        accounts = new ArrayList<>();
                        accountsByUserId.put(account.userId, accounts);
                    }
                    accounts.add(account);
                } else {
                    invalid = true;
                }
            }
            lastAccountChangeTime = dest.readLong();
            if (invalid) {
                saveAllAccounts();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dest.recycle();
        }
    }
}
 
Example 18
Project: nifi-android-s2s   File: SiteToSiteDB.java   View Source Code Vote up 4 votes
/**
 * Gets the peer status for a given url set and proxy
 *
 * @param siteToSiteClientConfig the config to get peer status for
 */
public void updatePeerStatusOnConfig(SiteToSiteClientConfig siteToSiteClientConfig) throws SQLiteIOException {
    SQLiteDatabase readableDatabase = sqLiteOpenHelper.getReadableDatabase();
    try {
        for (SiteToSiteRemoteCluster siteToSiteRemoteCluster : siteToSiteClientConfig.getRemoteClusters()) {
            PeerStatus origPeerStatus = siteToSiteRemoteCluster.getPeerStatus();

            List<String> parameters = new ArrayList<>();

            String peerUrlsString = getPeerUrlsString(siteToSiteRemoteCluster.getUrls());
            StringBuilder queryString = new StringBuilder(PEER_STATUS_URLS_COLUMN).append(" = ? AND ").append(PEER_STATUS_PROXY_HOST_COLUMN);
            parameters.add(peerUrlsString);

            String proxyHost = siteToSiteRemoteCluster.getProxyHost();
            if (proxyHost == null || proxyHost.isEmpty()) {
                queryString.append(" IS NULL AND ").append(PEER_STATUS_PROXY_PORT_COLUMN).append(" IS NULL");
            } else {
                queryString.append(" = ? AND ").append(PEER_STATUS_PROXY_PORT_COLUMN).append(" = ?");
                parameters.add(proxyHost);
                parameters.add(Integer.toString(siteToSiteRemoteCluster.getProxyPort()));
            }
            Cursor cursor;
            cursor = readableDatabase.query(false, PEER_STATUSES_TABLE_NAME, new String[]{CONTENT_COLUMN}, queryString.toString(),
                    parameters.toArray(new String[parameters.size()]), null, null, null, null);
            try {
                int contentIndex = cursor.getColumnIndexOrThrow(CONTENT_COLUMN);
                while (cursor.moveToNext()) {
                    byte[] bytes = cursor.getBlob(contentIndex);
                    Parcel parcel = Parcel.obtain();
                    parcel.unmarshall(bytes, 0, bytes.length);
                    parcel.setDataPosition(0);
                    PeerStatus dbPeerStatus = PeerStatus.CREATOR.createFromParcel(parcel);
                    if (dbPeerStatus != null && (origPeerStatus == null || origPeerStatus.getLastPeerUpdate() < dbPeerStatus.getLastPeerUpdate())) {
                        siteToSiteRemoteCluster.setPeerStatus(dbPeerStatus);
                        origPeerStatus = dbPeerStatus;
                    }
                }
            } finally {
                cursor.close();
            }
        }
    } catch (SQLiteException e) {
        throw new SQLiteIOException("Unable to read peer status from database.", e);
    } finally {
        readableDatabase.close();
    }
}
 
Example 19
Project: GitHub   File: ParcelUtils.java   View Source Code Vote up 4 votes
public static Parcelable parcelableReadFromParcel(Parcel parcel, Class<?> parcelableType, Parcelable parcelable) {
    parcel.setDataPosition(0);
    return createFromParcelFromParcelable(parcel, parcelable);
}
 
Example 20
Project: GravityBox   File: ProgressBarController.java   View Source Code Vote up 4 votes
private ProgressInfo getProgressInfo(String id, Notification n) {
    if (id == null || n == null) return null;

    ProgressInfo pInfo = new ProgressInfo(id, false, 0, 0);

    // We have to extract the information from the content view
    RemoteViews views = n.bigContentView;
    if (views == null) views = n.contentView;
    if (views == null) return pInfo;

    try {
        @SuppressWarnings("unchecked")
        List<Parcelable> actions = (List<Parcelable>) 
            XposedHelpers.getObjectField(views, "mActions");
        if (actions == null) return pInfo;

        for (Parcelable p : actions) {
            Parcel parcel = Parcel.obtain();
            p.writeToParcel(parcel, 0);
            parcel.setDataPosition(0);

            // The tag tells which type of action it is (2 is ReflectionAction)
            int tag = parcel.readInt();
            if (tag != 2)  {
                parcel.recycle();
                continue;
            }

            parcel.readInt(); // skip View ID
            String methodName = parcel.readString();
            if ("setMax".equals(methodName)) {
                parcel.readInt(); // skip type value
                pInfo.max = parcel.readInt();
                if (DEBUG) log("getProgressInfo: total=" + pInfo.max);
            } else if ("setProgress".equals(methodName)) {
                parcel.readInt(); // skip type value
                pInfo.progress = parcel.readInt();
                pInfo.hasProgressBar = true;
                if (DEBUG) log("getProgressInfo: current=" + pInfo.progress);
            }

            parcel.recycle();
        }
    } catch (Throwable  t) {
        XposedBridge.log(t);
    }

    return pInfo;
}