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

The following examples show how to use android.os.Parcel#setDataPosition() . These examples are extracted from open source projects. 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 Project: Lucid-Browser   File: BundleManager.java    License: Apache License 2.0 6 votes vote down vote up
public Bundle restoreFromPreferences() {
    Bundle bundle = null;
    SharedPreferences settings = activity.getSharedPreferences("instance", 0);
    String serialized = settings.getString("parcel", null);

    if (serialized != null) {
        Parcel parcel = Parcel.obtain();
        try {
            byte[] data = Base64.decode(serialized, 0);
            parcel.unmarshall(data, 0, data.length);
            parcel.setDataPosition(0);
            bundle = parcel.readBundle();
        } finally {
            parcel.recycle();
        }
    }
    return bundle;
}
 
Example 2
@Test
public void parcelsCorrectly() throws JSONException {
    JSONObject errorResponse = new JSONObject(stringFromFixture("errors/credit_card_error_response.json"));
    List<BraintreeError> errors = BraintreeError.fromJsonArray(errorResponse.getJSONArray("fieldErrors"));
    assertEquals(1, errors.size());
    BraintreeError error = errors.get(0);

    Parcel parcel = Parcel.obtain();
    error.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);

    BraintreeError parceled = BraintreeError.CREATOR.createFromParcel(parcel);

    assertEquals(error.getField(), parceled.getField());
    assertEquals(error.getMessage(), parceled.getMessage());
    assertEquals(error.getFieldErrors().size(), parceled.getFieldErrors().size());
}
 
Example 3
@Test
public void writeToParcel_serializesCorrectly() throws JSONException {
    String paypalAccountResponse = stringFromFixture("payment_methods/paypal_account_response.json");
    JSONObject creditFinancingJsonObject = new JSONObject(paypalAccountResponse).getJSONArray("paypalAccounts")
            .getJSONObject(0).getJSONObject("details").getJSONObject("creditFinancingOffered");

    PayPalCreditFinancing preSerialized = PayPalCreditFinancing.fromJson(creditFinancingJsonObject);
    Parcel parcel = Parcel.obtain();
    preSerialized.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);

    PayPalCreditFinancing payPalCreditFinancing = PayPalCreditFinancing.CREATOR.createFromParcel(parcel);

    assertNotNull(payPalCreditFinancing);
    assertFalse(payPalCreditFinancing.isCardAmountImmutable());
    assertEquals(18, payPalCreditFinancing.getTerm());
    assertTrue(payPalCreditFinancing.hasPayerAcceptance());
    assertEquals("USD", payPalCreditFinancing.getMonthlyPayment().getCurrency());
    assertEquals("USD", payPalCreditFinancing.getTotalCost().getCurrency());
    assertEquals("USD", payPalCreditFinancing.getTotalInterest().getCurrency());
    assertEquals("13.88", payPalCreditFinancing.getMonthlyPayment().getValue());
    assertEquals("250.00", payPalCreditFinancing.getTotalCost().getValue());
    assertEquals("0.00", payPalCreditFinancing.getTotalInterest().getValue());
}
 
Example 4
Source Project: braintree_android   File: ResultUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void success_parcelsCorrectly() throws JSONException {
    JSONObject response = new JSONObject()
            .put("access_token", "access_token");
    Result result = new Result("test", ResponseType.web, response, "[email protected]");
    Parcel parcel = Parcel.obtain();
    result.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);

    Result parceledResult = Result.CREATOR.createFromParcel(parcel);

    assertEquals(ResultType.Success, parceledResult.getResultType());
    assertNull(parceledResult.getError());
    JSONObject responseJson = result.getResponse();
    assertEquals("access_token", responseJson.getJSONObject("response").getString("access_token"));
    assertEquals("test", responseJson.getJSONObject("client").getString("environment"));
    assertEquals("web", responseJson.getString("response_type"));
    assertEquals("[email protected]", responseJson.getJSONObject("user").getString("display_string"));
}
 
Example 5
@MediumTest
@Test
public void testContentValues() {
    ContentValues values = new ContentValues();
    values.put("string", "value");
    assertEquals("value", values.getAsString("string"));
    byte[] bytes = new byte[42];
    Arrays.fill(bytes, (byte) 0x28);
    values.put("byteArray", bytes);
    assertTrue(Arrays.equals(bytes, values.getAsByteArray("byteArray")));

    // Write the ContentValues to a Parcel and then read them out
    Parcel p = Parcel.obtain();
    values.writeToParcel(p, 0);
    p.setDataPosition(0);
    values = ContentValues.CREATOR.createFromParcel(p);

    // Read the values out again and make sure they're the same
    assertTrue(Arrays.equals(bytes, values.getAsByteArray("byteArray")));
    assertEquals("value", values.get("string"));
}
 
Example 6
public void testInsertParcelableCreator() {
	final Uri uri = Uri.parse("content://empty");
	final ContentValues[] values = { new ContentValues() };

	final Insert request = new Insert(uri, values);

	final Parcel parcel = Parcel.obtain();
	request.writeToParcel(parcel, 0);
	parcel.setDataPosition(0);

	final Insert parceled = Insert.CREATOR.createFromParcel(parcel);
	assertEquals(uri, parceled.getUri());
	assertTrue(Arrays.deepEquals(values, parceled.getContentValues()));

	parcel.recycle();
}
 
Example 7
@Test
public void parcels() {
    BillingAgreementRequest request = new BillingAgreementRequest();
    request.environment("test");
    request.clientId("client-id");
    request.pairingId(RuntimeEnvironment.application, "pairing-id");
    request.clientMetadataId("client-metadata-id");
    request.cancelUrl("com.braintreepayments.demo.braintree.cancel", "cancel");
    request.successUrl("com.braintreepayments.demo.braintree.success", "success");
    request.approvalURL("com.braintreepayments.demo.braintree.approval-url://?ba_token=TOKEN");

    Parcel parcel = Parcel.obtain();
    request.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);
    CheckoutRequest parceledRequest = CheckoutRequest.CREATOR.createFromParcel(parcel);

    assertEquals("test", parceledRequest.getEnvironment());
    assertEquals("client-id", parceledRequest.getClientId());
    assertEquals("client-metadata-id", parceledRequest.getClientMetadataId());
    assertEquals("pairing-id", parceledRequest.getPairingId());
    assertEquals("com.braintreepayments.demo.braintree.cancel://onetouch/v1/cancel", parceledRequest.getCancelUrl());
    assertEquals("com.braintreepayments.demo.braintree.success://onetouch/v1/success", parceledRequest.getSuccessUrl());
    assertEquals("com.braintreepayments.demo.braintree.approval-url://?ba_token=TOKEN", parceledRequest.mApprovalUrl);
    assertEquals("ba_token", parceledRequest.mTokenQueryParamKey);
}
 
Example 8
Source Project: FlowGeek   File: ParcelFn.java    License: GNU General Public License v2.0 5 votes vote down vote up
static <T> T unmarshall(byte[] array) {
    Parcel parcel = Parcel.obtain();
    parcel.unmarshall(array, 0, array.length);
    parcel.setDataPosition(0);
    Object value = parcel.readValue(CLASS_LOADER);
    parcel.recycle();
    return (T)value;
}
 
Example 9
Source Project: parceler   File: ParcelExperiment.java    License: Apache License 2.0 5 votes vote down vote up
public void run(){
    Parcel parcel = Parcel.obtain();

    long start = System.nanoTime();
    for (int i = 0; i < ITERS; i++) {

        mutator.write(parcel);

        parcel.setDataPosition(0);

        mutator.read(parcel);
    }
    long total = System.nanoTime() - start;
    double timePer = 1.0 * total / ITERS;


    long writeStart = System.nanoTime();
    for (int i = 0; i < ITERS; i++) {
        mutator.write(parcel);
    }
    long writeTotal = System.nanoTime() - writeStart;
    double writeTime = 1.0 * writeTotal / ITERS;

    mutator.write(parcel);

    long readStart = System.nanoTime();
    for (int i = 0; i < ITERS; i++) {

        parcel.setDataPosition(0);

        mutator.read(parcel);
    }
    long reatTotal = System.nanoTime() - readStart;
    double readTime = 1.0 * reatTotal / ITERS;

    String output = name + " Total Time: " + timePer + " write: " + writeTime + " read: " + readTime;

    Toast.makeText(context, output, 1000).show();
    Log.i("Parceler", output);
}
 
Example 10
Source Project: letv   File: MediaMetadataCompat.java    License: Apache License 2.0 5 votes vote down vote up
public static MediaMetadataCompat fromMediaMetadata(Object metadataObj) {
    if (metadataObj == null || VERSION.SDK_INT < 21) {
        return null;
    }
    Parcel p = Parcel.obtain();
    MediaMetadataCompatApi21.writeToParcel(metadataObj, p, 0);
    p.setDataPosition(0);
    MediaMetadataCompat metadata = (MediaMetadataCompat) CREATOR.createFromParcel(p);
    p.recycle();
    metadata.mMetadataObj = metadataObj;
    return metadata;
}
 
Example 11
public void testQueryParcelableCreator() {
	final Uri uri = Uri.parse("content://empty");
	final String[] projection = { "_id" };
	final String where = "test = ?";
	final String[] whereArgs = { "true" };
	final String sortOrder = "_id desc";
	final boolean forceUpdate = true;

	final Query request = new Query(uri);
	request.setProjection(projection);
	request.setWhere(where, whereArgs);
	request.setSortOrder(sortOrder);
	request.setForceUpdate(forceUpdate);

	final Parcel parcel = Parcel.obtain();
	request.writeToParcel(parcel, 0);
	parcel.setDataPosition(0);

	final Query parceled = Query.CREATOR.createFromParcel(parcel);
	assertEquals(uri, parceled.getUri());
	assertTrue(Arrays.deepEquals(projection, parceled.getProjection()));
	assertEquals(where, parceled.getWhereClause());
	assertTrue(Arrays.deepEquals(whereArgs, parceled.getWhereArgs()));
	assertEquals(sortOrder, parceled.getSortOrder());
	assertEquals(forceUpdate, parceled.shouldForceUpdate());

	parcel.recycle();
}
 
Example 12
Source Project: paperparcel   File: TypeAdapterTest.java    License: Apache License 2.0 5 votes vote down vote up
private static <A extends TypeAdapter<T>, T> T writeThenRead(A adapter, T input) {
  Parcel parcel = Parcel.obtain();
  adapter.writeToParcel(input, parcel, 0);
  parcel.setDataPosition(0);
  T result = adapter.readFromParcel(parcel);
  parcel.recycle();
  return result;
}
 
Example 13
Source Project: fingen   File: ParcelableHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link #immediateDeepCopy(android.os.Parcelable)}, but for when you need a little
 * more control over which ClassLoader will be used.
 */
public static Parcelable immediateDeepCopy(Parcelable input, ClassLoader classLoader) {
    Parcel parcel = null;
    try {
        parcel = Parcel.obtain();
        parcel.writeParcelable(input, 0);
        parcel.setDataPosition(0);
        return parcel.readParcelable(classLoader);
    } finally {
        if (parcel != null) {
            parcel.recycle();
        }
    }
}
 
Example 14
@Test
public void captureConfigurationCanBeParcelized() throws Exception {
    CaptureConfiguration config = new CaptureConfiguration(CaptureResolution.RES_360P, CaptureQuality.MEDIUM);

    Parcel parcel = Parcel.obtain();
    config.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);
    CaptureConfiguration restoredConfiguration = CaptureConfiguration.CREATOR.createFromParcel(parcel);

    checkConfiguration(restoredConfiguration, config.getVideoWidth(), config.getVideoHeight(), config.getVideoBitrate(),
            config.getMaxCaptureDuration(), config.getMaxCaptureFileSize());
}
 
Example 15
Source Project: android_9.0.0_r45   File: ZenModeConfig.java    License: Apache License 2.0 5 votes vote down vote up
public ZenModeConfig copy() {
    final Parcel parcel = Parcel.obtain();
    try {
        writeToParcel(parcel, 0);
        parcel.setDataPosition(0);
        return new ZenModeConfig(parcel);
    } finally {
        parcel.recycle();
    }
}
 
Example 16
Source Project: android-sdk   File: SQLiteStore.java    License: MIT License 4 votes vote down vote up
public static Parcel unmarshall(byte[] bytes) {
    Parcel parcel = Parcel.obtain();
    parcel.unmarshall(bytes, 0, bytes.length);
    parcel.setDataPosition(0);
    return parcel;
}
 
Example 17
@Test
public void isParcelable() {
    Cart cart = Cart.newBuilder()
            .setTotalPrice("5.00")
            .build();
    GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest()
            .transactionInfo(TransactionInfo.newBuilder()
                    .setTotalPrice("10")
                    .setCurrencyCode("USD")
                    .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                    .build())
            .emailRequired(true);

    PayPalRequest paypalRequest = new PayPalRequest("10")
            .currencyCode("USD");

    ThreeDSecureRequest threeDSecureRequest = new ThreeDSecureRequest()
            .nonce("abc-123")
            .versionRequested(ThreeDSecureRequest.VERSION_2)
            .amount("10.00")
            .email("[email protected]")
            .mobilePhoneNumber("3125551234")
            .billingAddress(new ThreeDSecurePostalAddress()
                    .givenName("Given")
                    .surname("Surname")
                    .streetAddress("555 Smith St.")
                    .extendedAddress("#5")
                    .locality("Chicago")
                    .region("IL")
                    .postalCode("54321")
                    .countryCodeAlpha2("US")
                    .phoneNumber("3125557890")
            )
            .additionalInformation(new ThreeDSecureAdditionalInformation()
                    .shippingMethodIndicator("GEN")
            );

    DropInRequest dropInRequest = new DropInRequest()
            .tokenizationKey(TOKENIZATION_KEY)
            .collectDeviceData(true)
            .amount("1.00")
            .googlePaymentRequest(googlePaymentRequest)
            .disableGooglePayment()
            .paypalRequest(paypalRequest)
            .disablePayPal()
            .disableVenmo()
            .disableCard()
            .requestThreeDSecureVerification(true)
            .threeDSecureRequest(threeDSecureRequest)
            .maskCardNumber(true)
            .maskSecurityCode(true)
            .vaultManager(true)
            .vaultCard(true)
            .allowVaultCardOverride(true)
            .cardholderNameStatus(CardForm.FIELD_OPTIONAL);

    Parcel parcel = Parcel.obtain();
    dropInRequest.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);
    DropInRequest parceledDropInRequest = DropInRequest.CREATOR.createFromParcel(parcel);

    assertEquals(TOKENIZATION_KEY, parceledDropInRequest.getAuthorization());
    assertTrue(parceledDropInRequest.shouldCollectDeviceData());
    assertEquals("1.00", parceledDropInRequest.getAmount());
    assertEquals("10", dropInRequest.getGooglePaymentRequest().getTransactionInfo().getTotalPrice());
    assertEquals("USD", dropInRequest.getGooglePaymentRequest().getTransactionInfo().getCurrencyCode());
    assertEquals(WalletConstants.TOTAL_PRICE_STATUS_FINAL, dropInRequest.getGooglePaymentRequest().getTransactionInfo().getTotalPriceStatus());
    assertTrue(dropInRequest.getGooglePaymentRequest().isEmailRequired());
    assertEquals("10", dropInRequest.getPayPalRequest().getAmount());
    assertEquals("USD", dropInRequest.getPayPalRequest().getCurrencyCode());
    assertFalse(dropInRequest.isGooglePaymentEnabled());
    assertFalse(parceledDropInRequest.isPayPalEnabled());
    assertFalse(parceledDropInRequest.isVenmoEnabled());
    assertFalse(parceledDropInRequest.isCardEnabled());
    assertTrue(parceledDropInRequest.shouldRequestThreeDSecureVerification());
    assertEquals("abc-123", dropInRequest.getThreeDSecureRequest().getNonce());
    assertEquals("2", dropInRequest.getThreeDSecureRequest().getVersionRequested());
    assertEquals("10.00", dropInRequest.getThreeDSecureRequest().getAmount());
    assertEquals("[email protected]", dropInRequest.getThreeDSecureRequest().getEmail());
    assertEquals("3125551234", dropInRequest.getThreeDSecureRequest().getMobilePhoneNumber());
    assertEquals("Given", dropInRequest.getThreeDSecureRequest().getBillingAddress().getGivenName());
    assertEquals("Surname", dropInRequest.getThreeDSecureRequest().getBillingAddress().getSurname());
    assertEquals("555 Smith St.", dropInRequest.getThreeDSecureRequest().getBillingAddress().getStreetAddress());
    assertEquals("#5", dropInRequest.getThreeDSecureRequest().getBillingAddress().getExtendedAddress());
    assertEquals("Chicago", dropInRequest.getThreeDSecureRequest().getBillingAddress().getLocality());
    assertEquals("IL", dropInRequest.getThreeDSecureRequest().getBillingAddress().getRegion());
    assertEquals("54321", dropInRequest.getThreeDSecureRequest().getBillingAddress().getPostalCode());
    assertEquals("US", dropInRequest.getThreeDSecureRequest().getBillingAddress().getCountryCodeAlpha2());
    assertEquals("3125557890", dropInRequest.getThreeDSecureRequest().getBillingAddress().getPhoneNumber());
    assertEquals("GEN", dropInRequest.getThreeDSecureRequest().getAdditionalInformation().getShippingMethodIndicator());
    assertTrue(parceledDropInRequest.shouldMaskCardNumber());
    assertTrue(parceledDropInRequest.shouldMaskSecurityCode());
    assertTrue(parceledDropInRequest.isVaultManagerEnabled());
    assertTrue(parceledDropInRequest.getDefaultVaultSetting());
    assertTrue(parceledDropInRequest.isSaveCardCheckBoxShown());
    assertEquals(CardForm.FIELD_OPTIONAL, parceledDropInRequest.getCardholderNameStatus());
}
 
Example 18
Source Project: paperparcel   File: PaperParcelTask.java    License: Apache License 2.0 4 votes vote down vote up
@Override protected int writeThenRead(PaperParcelResponse response, Parcel parcel) {
  parcel.writeParcelable(response, 0);
  parcel.setDataPosition(0);
  PaperParcelResponse out = parcel.readParcelable(PaperParcelResponse.class.getClassLoader());
  return out.getUsers().size();
}
 
Example 19
Source Project: Silence   File: ParcelUtil.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static Parcel deserialize(byte[] bytes) {
  Parcel parcel = Parcel.obtain();
  parcel.unmarshall(bytes, 0, bytes.length);
  parcel.setDataPosition(0);
  return parcel;
}
 
Example 20
public static Config fromByteArray (byte[] byteArray) {
    Parcel parcel = Parcel.obtain();
    parcel.unmarshall(byteArray, 0, byteArray.length);
    parcel.setDataPosition(0);
    return Config.CREATOR.createFromParcel(parcel);
}