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

The following examples show how to use android.os.Parcel#setDataPosition() . 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: BraintreeErrorUnitTest.java    From braintree_android with MIT License 6 votes vote down vote up
@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 2
Source File: BillingAgreementRequestUnitTest.java    From braintree_android with MIT License 6 votes vote down vote up
@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 3
Source File: InsertTest.java    From arca-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 4
Source File: DatabaseGeneralTest.java    From sqlite-android with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: ResultUnitTest.java    From braintree_android with 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 6
Source File: PayPalCreditFinancingUnitTest.java    From braintree_android with MIT License 6 votes vote down vote up
@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 7
Source File: BundleManager.java    From Lucid-Browser with 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 8
Source File: ParcelExperiment.java    From parceler with 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 9
Source File: MediaMetadataCompat.java    From letv with 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 10
Source File: QueryTest.java    From arca-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 11
Source File: TypeAdapterTest.java    From paperparcel with 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 12
Source File: ParcelableHelper.java    From fingen with 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 13
Source File: CaptureConfigurationTest.java    From LandscapeVideoCamera with Apache License 2.0 5 votes vote down vote up
@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 14
Source File: ParcelFn.java    From FlowGeek with 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 15
Source File: ZenModeConfig.java    From android_9.0.0_r45 with 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 File: DropInRequestUnitTest.java    From braintree-android-drop-in with MIT License 4 votes vote down vote up
@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 17
Source File: SQLiteStore.java    From android-sdk with 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 18
Source File: PaperParcelTask.java    From paperparcel with 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 File: ParcelUtil.java    From Silence with 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
Source File: Config.java    From background-geolocation-android with Apache License 2.0 4 votes vote down vote up
public static Config fromByteArray (byte[] byteArray) {
    Parcel parcel = Parcel.obtain();
    parcel.unmarshall(byteArray, 0, byteArray.length);
    parcel.setDataPosition(0);
    return Config.CREATOR.createFromParcel(parcel);
}