Mobile SDK end-of-life has been announced and scheduled for the end of 2023, in favor of updated and more streamlined app personalization using server-side APIs.
Basic Methods
Requires SDK version 3.6.0
Sets the API identifier in order to log the data to the correct Dynamic Yield account and site. Returns an instance of the class DYApi. This should be the first call to:
public static DYApi setContextAndSecret(Context context,String secret,DYSetSecretResult completionHandler)
Parameters
- context: The application context.
- secret: String key, created in the Dynamic Yield admin console.
- completionHandler: A runnable that is called with the results of the Dynamic Yield SDK initialization results (the same as the parameters for experimentReadyWithState). This can be used instead of implementing the listener method experimentsReadyWithState.
Example
DYApi.setContextAndSecret(getApplicationContext(),"123456789123456789123456789", new DYSetSecretResult() {
@Override
public void onEnd(DYExperimentsState state) {
if (state == DYExperimentsState.DY_READY_NO_UPDATE_NEEDED || state == DYExperimentsState.DY_READY_AND_UPDATED) {
//start running experiments
}
}
});
Main method returning the shared instance of the Dynamic Yield SDK. Use this only after calling.
setContextAndSecret.public static DYApi getInstance()
Example
DYApi mDYApi = DYApi.getInstance();
Sets a listener object (listener) to receive notifications from DYApi. Returns true if the the listener is valid.
public boolean setListener(com.dynamicyield.listener.DYListenerItf listener)
Parameter
- listener: The listener object
Example
DYApi.getInstance().setListener(listener);
public void enableDeveloperLogs(boolean enabled);
Parameter
- enabled: True will enable the developer logs
Example
DYApi.getInstance().enableDeveloperLogs(true);
Listener Interface
A listener class for receiving information about DYApi state.
experimentsReadyWithState
Called when experiments have been updated and are ready to use, with detailed state.
public void experimentsReadyWithState(DYExperimentsState dyExperimentsState)
Parameters
- dyExperimentsState: An enum holding the state with the following possible values:
- DY_NOT_READY experiments are not ready to use
- DY_READY_LOCAL_CACHE experiments loaded from local cache
- DY_READY_AND_UPDATED experiments were updated from the server and are ready to use
- DY_READY_NO_UPDATE_NEEDED experiments loaded from local cache and no other updates are needed
Example
@Override
public void experimentsReadyWithState(DYExperimentsState dyExperimentsState) {
if (dyExperimentsState == DYExperimentsState.DY_READY_NO_UPDATE_NEEDED || dyExperimentsState == DYExperimentsState.DY_READY_AND_UPDATED) {
//..do something
}
}
User Data
Requires SDK version 3.7.0
Expose the user affinity profile.
public void getUserAffinityProfile(final DYJsonObjectResult callback);
Parameter
- callback: A runnable that is called when the data is received.
Example
DYApi.getInstance().getUserAffinityProfile(
new DYJsonObjectResult() {
@Override
public void onEnd(JSONObject json) {
//do something with result
}
});
Used to identify the user across platforms (e.g. web, iOS, CRM, email); returns Yes if identifiers is not null or empty. We recommend calling this method wherever the user enters their customer ID (e.g. checkout).
public boolean identifyUser(com.dynamicyield.userdata.external.DYUserData userAttributes)
Parameter
- userAttributes: Object of class DYUserData, holds basic identification attributes about the user
Example
DYUserData userData = new DYUserData();
userData.setEmail("18B258E9ADE091623DD829132E1E9D8B4A7F7D90ABEA194001C54341C3F27B79");
DYApi.getInstance().identifyUser(userData);
Return the user ID generated by Dynamic Yield.
-(NSString* _Nullable)getDYID;
Example
String userID = DYApi.getInstance().getDYId();
Requires SDK version 3.7.0
Return the user ID generated by Dynamic Yield.
public void getDYId(final DYStringParamHandler callback);
Parameter
- callback: A runnable that is called when the data is received.
Example
DYApi.getInstance().getDYId(new DYStringParamHandler() {
@Override
public void onEnd(String name) {
//do something with result
}
});
Requires SDK version 3.7.0
Returns an array of audiences to which to user is assigned from the Dynamic Yield server, or Null if no audience is available.
public void getUserAudiences(final DYJsonArrayResult callback);
Parameter
- callback: A runnable that is called when the data is received.
Example
DYApi.getInstance().getUserAudiences(new DYJsonArrayResult() {
@Override
public void onEnd(JSONArray array) {
//do something with result
}
});
Indicates that a user has consented to allow Dynamic Yield to collect and use their personal data.
- Opting out prevents future data collection from the current device/browser from all sections of the account, across all domains. This method overrides any past opt-in methods.
- If the visitor had opted out in the past, opting in will allow data collection moving forward.
For more details, see Visitor Data Privacy Management (GDPR Support).
Example
DYApi.getInstance().consentOptin();
Indicates that a user does not want Dynamic Yield to collect and use their personal data.
- Opting out prevents future data collection from the current device/browser from all sections of the account, across all domains. This method overrides any past opt-in methods.
- If the visitor had opted out in the past, opting in will allow data collection moving forward.
For more details, see Visitor Data Privacy Management (GDPR Support).
Example
DYApi.getInstance().consentOptout();
Returns the views and purchases of one or more products over different time periods.
Function Declaration
public boolean getProductActivityData(JSONArray skus, JSONArray timeframes, String includeProductInterest, boolean includeProductData, DYProductActivityDataListener listener)
Parameters
- skus: Array of product SKUs
- timeframes: An array of one or more values defining the timeframe going back. If undefined, returns values for all time periods. The values can be:
- DYProductActivityDataValues.TIME_FRAME_DAILY
- DYProductActivityDataValues.TIME_FRAME_TWO_DAYS
- DYProductActivityDataValues.TIME_FRAME_WEEKLY
- DYProductActivityDataValues.TIME_FRAME_TWO_WEEKS
- DYProductActivityDataValues.TIME_FRAME_MONTHLY
- includeProductInterest: Determines if viewing data, purchase data, or both are returned. If undefined, both are returned. The values can be:
- DYProductActivityDataValues.PRODUCT_INTEREST_VIEW
- DYProductActivityDataValues.PRODUCT_INTEREST_PURCHASE
- includeProductData: Determines whether or not to display product attributes and details such as color, style, etc. The values can be YES or NO.
- listener: a class instance that implements DYProductActivityDataDelegate Protocol
Example
JSONArray timeFrame = new JSONArray();
timeFrame.put(DYProductActivityDataValues.TIME_FRAME_DAILY);
JSONArray skus = new JSONArray();
skus.put("1");
DYApi.getInstance().getProductActivityData(skus, timeFrame, DYProductActivityDataValues.PRODUCT_INTEREST_VIEW, true, this);
Analytics
Requires SDK version 3.6.0
Reports an event to the Dynamic Yield server; returns true if eventName is not null or empty.
public boolean trackEvent(String eventName, JSONObject properties , DYTrackResult completionHandler)
Parameters
- eventName: The unique name of the event as maintained in the Dynamic Yield Admin console.
- properties: Event properties JSON object containing key value pairs, keys the event properties are as maintained in the Dynamic Yield Admin console.
- completionHandler: A runnable that is called when the event is received and ready to be used. This is used to wait for the event data to be available before running something that is dependent on that data (like a Dynamic Content campaign).
Example
try {
JSONObject props = new JSONObject();
props.putOpt("name","purchase");
DYApi.getInstance().trackEvent("button clicked",props, new DYTrackResult() {
@Override
public void onEnd(String name) {
//run an experiment
}});
} catch (JSONException e) {
}
Requires SDK version 3.6.0
Reports an application page view to the Dynamic Yield server; returns true if the uniqueID parameter is not null or empty.
public boolean trackPageView( String uniqueID, DYPageContext context, DYTrackResult completionHandler )
Parameters
- uniqueId: Unique identifier of the page as maintained in the application
- context: (Optional) The current screen’s context, for details see Page Context for Mobile.
- completionHandler: A runnable that is called when the pageview data is received by Dynamic Yield and ready to be used. This is used to wait for the pageview data to be available before running something that is dependent on that data (like a Dynamic Content campaign).
Example
DYApi.getInstance().trackPageView("homepage", new DYPageContext("en_US", DYPageContext.HOMEPAGE, null), new DYTrackResult() {
@Override
public void onEnd(String name) {
//run an experiment
}
});
Requires SDK version 3.6.0
Sets the evaluator value, will remain valid until set again or until the session ends; returns Yes if input parameters are not nil or empty.
public boolean setEvaluator(String evaluatorID, JSONArray params, boolean saveBetweenSessions, DYEvaluatorSet completionHandler )
Parameters
- key: The evaluator ID from DY’s admin console
- params: Array of the evaluator value(s)
- saveBetweenSessions: true for saving the evaluator value between sessions, false to clear the value when a new session starts
- completionHandler: A runnable that is called when the evaluator is set and ready to be used. This is used to wait for the evaluator to be set before running something that is dependent on the evaluator results (like a Dynamic Content campaign).
Example
try {
DYApi.getInstance().setEvaluator("123456", new JSONArray("[\"red\"]"), false, new DYEvaluatorSet() {
@Override
public void onEvaluatorSet(String evaluatorID, JSONArray evaluatorValue, boolean isPersistent) {
//run an experiment
}});
} catch (JSONException ignored) {
}
Messaging and Custom Actions
Requires SDK version 2.2
A delegate / listener method that allows you to control and manage content returned from a Messaging Overlay or Custom Action.
public void onSmartActionReturned( String smartActionId, JSONObject smartActionData );
This method is called after an Overlay or Custom Action has been triggered and a variation has been selected by Dynamic Yield. For Custom Actions the implementation of the method should include the desired app manipulation based on the JSON data returned. For Overlays where ‘shouldDYRender’ was set to ‘false’, this method allows manipulation and custom rendering based on the HTML data returned by Dynamic Yield.
Parameters
- smartActionId: The Smart Action ID as maintained in the Dynamic Yield Admin Console
- smartActionData: The variation data as maintained in the Dynamic Yield Admin Console; this can be either the Messaging Overlay HTML or the Custom Action JSON.
Example
try {
if (smartActionID.equals("Homepage order")) {
setHomePageOrder(smartActionData.get("variationData"));
}
} catch (JSONException e) {
}
For HTML Overlays, we provide a dedicated URI enabling closing the overlay: simply add “dycloseoverlay=true” as a URI parameter (e.g.:<your app>://<your deep link>?dycloseoverlay=true). Triggering this URI from within the Overlay’s HTML will close the overlay. This can be called using an href or using Javascript.
Variable Sets
Requires SDK version 1.8
Requires SDK version 3.7.0
Returns the value assigned to a variable name specified in parameter varName. The value is maintained in Dynamic Yield’s admin console. If there is no value assigned, the value specified in parameter defaultValue will be used. Notice the value will be returned with type Object.
public void getSmartVariable(final String varName, final DYObjectResult callback);
Parameters
- varName: The name of the variable as maintained in the Dynamic Yield Admin Console
- defaultValue: The value that should be assigned to the variable in case no value is returned (e.g. the variable has been archived or deleted in the Dynamic Yield admin console). The value can be null, but make sure that this does not negatively impact your app.
- callback: A runnable that is called when the data is received.
Example
DYApi.getInstance().getSmartVariable("splashScreenText", new DYObjectResult() {
@Override
public void onEnd(Object object) {
//do something with result
}
});
Dynamic Content
Requires SDK version 1.9
Requires SDK version 3.6.0
Selects an HTML variation from the Dynamic Content defined in smartObjID and then assigns it to the webview container defined in webView. Returns true if the input parameters are valid. If parameter fallBackURL is maintained, the HTML content retrieved from the URL will be assigned to the webview container in case no variation is returned from the Dynamic Yield server and in case the control group variation was selected.
public void loadSmartObject(ImageView imageView, final String smartObjectId, final String fallbackUrl, DYLoadSmartObjectResult completionHandler)
Parameters
- webView: The webview to which the Dynamic Content variation HTML content should be assigned
- smartObjId: The Dynamic Content ID or name as maintained in the Dynamic Yield admin console)
- fallbackURL: A URL to the HTML content that should be loaded to the web view in case no Dynamic Content variation is returned from Dynamic Yield
- completionHandler: A runnable that is called with the data from the Dynamic Content campaign (the same as the parameters for onSmartObjectLoadResult). This can be used instead of implementing the listener method onSmartObjectLoadResult.
Example
DYApi.getInstance().loadSmartObject(imageview, "homepage banner", fallbackURL, new DYLoadSmartObjectResult() {
@Override
public void onSmartObjectLoadResult(String smartObjId, String html, View view) {
//hide loading icon
}
});
Requires SDK version 3.6.0
Selects an image variation from the Dynamic Content defined in smartObjID and then assigns it to the imageview container defined in imageView. Returns true if the input parameters are valid. Note that Dynamic Content variations with HTML content will not be rendered.
If parameter fallBackURL is maintained, the image retrieved from the URL will be assigned to the imageView container in case no variation is returned from the Dynamic Yield server and in case the control group variation was selected.
Note: Since this is an API for Dynamic Content with image content, use the Dynamic Yield template “Mobile Image” in all Dynamic Content variations.
Important: In order to avoid empty content, it is mandatory to either use Dynamic Content in a webView with existing content or to use a fallbackURL
public void loadSmartObject( ImageView imageView, final String smartObjectId, final String defaultUrl );
Parameters
- imageView: The image container to which the Dynamic Content image content should be loaded to
- smartObjId: The Dynamic Content ID or name as maintained in the Dynamic Yield admin console
- fallBackURL: A URL to an image that should be loaded to the image view in case no Dynamic Content variation is returned from Dynamic Yield
- completionHandler: A runnable that is called with the data from the Dynamic Content campaign (the same as the parameters for onSmartObjectLoadResult). This can be used instead of implementing the listener method onSmartObjectLoadResult.
Example
DYApi.getInstance().loadSmartObject(imageview, "homepage banner", fallbackURL, new DYLoadSmartObjectResult() {
@Override
public void onSmartObjectLoadResult(String smartObjId, String html, View view) {
//hide loading icon
}
});
A delegate method called with the return of a Dynamic Content variation. Enables responding to the returned content before rendering (e.g. do not render the webview if the result is empty for any reason).
public void onSmartObjectLoadResult( String smartObjId, String html, WebView webView );
Parameters
- smartObjId: The Dynamic Content ID or name as maintained in the Dynamic Yield admin console
- webView: The WebView to which the Dynamic Content HTML content is assigned
- html: The Dynamic Content variation HTML content returned by Dynamic Yield
Example
public void onSmartObjectLoadResult(String smartObjId, String html, WebView webView) {
if (!html) {
webView.setVisibility(View.GONE);
}
}
Requires SDK version 3.7.0
Chooses a Dynamic Content variation, returns the content as a JSON object, and reports an impression. If a user views the same variation more than once without calling the API again, call trackSmartObjectImpressions to report additional impressions. Call trackSmartObjectClicked every time a user clicks on a Dynamic Content variation created using the getSmartObjectData API to report a click.
public void getSmartObjectData(final String smartObjectID, final DYJsonObjectResult callback);
Parameter
- smartObjectID: The ID of the Dynamic Content campaign.
- callback: A runnable that is called when the data is received.
Example Call
DYApi.getInstance().getSmartObjectData("htmlContent", new DYJsonObjectResult() {
@Override
public void onEnd(JSONObject json) {
//do something with result
}
});
Return Value
A JSON object that contains the following items:
- params : The JSON object with all variables and values (the content from the Variables tab in the user interface when creating variations)
- selectedVar – The content of the HTML, CSS, and JS tabs from the user interface combined into one string
Reports to Dynamic Yield that a user viewed a Dynamic Content variation created by using the getSmartObjectData API. An impression is already counted every time a getSmartObjectData call is made, but if a user views the same variation more than once without calling getSmartObjectData again, call this API to report additional impressions.
public void trackSmartObjectImpression(String smartObjectID);
Parameter
- smartObjectID: The ID of the Dynamic Content campaign
Example Call
DYApi.getInstance().trackSmartObjectImpression("Your_Dynamic_Content_Campaign_ID");
Reports to Dynamic Yield that a user clicked on a Dynamic Content variation created by using the getSmartObjectData API.
public void trackSmartObjectClicked(String smartObjectID);
Parameter
- smartObjectID: The ID of the Dynamic Content campaign
Example Call
DYApi.getInstance().trackSmartObjectClick("Your_Dynamic_Content_Campaign_ID");
Push Notification
Requires SDK version 3.0
Pass the user’s device push token (PushID) to Dynamic Yield.
public boolean setPushNotificationId( String token )
Parameter
- token: The user’s push token.
Example
DYApi.getInstance().setPushNotificationId(token )
Opts the user into receiving Dynamic Yield’s triggered push notification.
public boolean subscribeToPushNotifications()
Example
DYApi.getInstance().subscribeToPushNotifications();
Opts the user out of receiving Dynamic Yield’s triggered push notification.
public boolean unSubscribeFromPushNotifications()
Example
DYApi.getInstance().unSubscribeFromPushNotifications();
Renders the Push notification.
public void handlePushNotificationMessage( RemoteMessage remoteMessage, Context ctx )
Example
DYApi.getInstance().handlePushMessage( remoteMessage, ctx );
Product Recommendations
Requires SDK version 2.0
Get the recommended items for a given widget id in a specified context. The results are returned via the listener.
public boolean sendRecommendationsRequest( String widgetId, DYPageContext context, boolean itemIDsOnly, DYRecommendationListenerItf rcomListener )
public boolean sendRecommendationsRequest( String widgetId, DYPageContext context, boolean itemIDsOnly, DYRecommendationListenerItf rcomListener, int pageNumber, int pageSize )
Parameters
- widgetId: The recommendation widget ID as maintained in the Dynamic Yield admin console
- context: The current screen’s context, see details in Dynamic Yield Context Object
- itemIDsOnly: Used to request only the recommended item’s identifiers (without additional item metadata).
- rcomListener: A listener that receives the results and handles the recommended items presentation, see onRecommendationResults
Pagination Parameters (beta)
The pagination parameters control how many recommendation items appear on each page, and define the page number when results are broken down into multiple pages. They only apply if the following conditions are met:
- Page type is homepage, category, or other
- Algorithm is popularity or user affinity, and the same algorithm is used for each slot
- There are no dynamic filters (no excludes, no shuffle, etc.)
- If any filtering rules are used, they must be of type “exclude” or “only include”, and must be applied to all slots.
The pagination parameters are :
- pageSize: determines the number of recommended items in each page
- pageNumber: determines the page number when recommendations results are broken down to multiple pages
Example
JSONArray data = new JSONArray();
data.put("101");
DYPageContext context = new DYPageContext( "en_GB", DYPageContext.PRODUCT, data );
DYApi.getInstance().sendRecommendationsRequest( "991", context, true, this );
DYApi.getInstance().sendRecommendationsRequest( "991", context, true, this, 1 ,5 );
Get the recommended items for a given widget id in a specified context. The results are returned via the listener according to the filter.
public boolean sendRecommendationsRequest(String widgetId, DYPageContext context, ArrayList<DYRcomFilter> filters, DYRecommendationListenerItf rcomListener)
Parameters
- widgetId: The recommendation widget ID as maintained in the Dynamic Yield admin console
- context: The current screen’s context. For details see DY Page Context class in Additional Classes below.
- filter: A filter that limits the results defined using the DYRCOMFilter class. For details, see Additional Classes below.
- rcomListener: A listener that receives the results and handles the recommended items presentation, see onRecommendationResults below.
Example
DYApi.getInstance().sendRecommendationsRequest("44435", new DYPageContext("en_US", DYPageContext.HOMEPAGE, null),new ArrayList<DYRcomFilter>(){{
JSONArray skus = new JSONArray();
skus.put("A1");
skus.put("A2");
add(new DYRcomFilter(DYRcomFilterField.DY_FILTER_SKU, DYRcomFilterType.DY_FILTER_EXCLUDE,skus));
JSONArray groupIDs = new JSONArray();
groupIDs.put("A5");
groupIDs.put("A6");
add(new DYRcomFilter(DYRcomFilterField.DY_FILTER_GROUP_ID, DYRcomFilterType.DY_FILTER_INCLUDE,groupIDs));
}}, new DYRecommendationListenerItf() {
@Override
public void onRecommendationResult(JSONArray recommendations, String widgetId) {
}
});
Get the recommended items for a given widget id in a specified context, only return products that adhere to a set of filters set in real-time. The results are returned via the listener. The function returns true if the parameters are valid, otherwise it returns false.
public boolean sendRecommendationsRequest(String widgetId, DYPageContext context, JSONArray realTimeFilters, DYRecommendationListenerItf rcomListener)
Parameters
- widgetId: The recommendation widget ID as maintained in the Dynamic Yield admin console
- context: The current screen’s context. For details see DY Page Context class in Additional Classes below.
- realTimeFilter: A list of real time filters that limits the results.
- rcomListener: A listener that receives the results and handles the recommended items presentation, see onRecommendationResults below.
Example
try {
JSONArray realtimeRules = new JSONArray("[{\"priority\":0,\"id\":-1,\"isContextAware\":false,\"query\":{\"conditions\":[{\"field\":\"sku\",\"arguments\":[{\"action\":\"IS\",\"value\":\"1002003-400\"}]}]},\"type\":\"include\",\"slots\":[0]}]");
DYApi.getInstance().sendRecommendationsRequest("31002", new DYPageContext("en_US", DYPageContext.HOMEPAGE, null), realtimeRules, new DYRecommendationListenerItf() {
@Override
public void onRecommendationResult(JSONArray recommendations, String widgetId) {
//do something with the results
}
});
} catch (JSONException e) {
e.printStackTrace();
}
A listener method called with the return of the recommendation results. This is where the rendering logic of the returned recommended items should take place. The response is an array of JSON objects, each item in the returned array includes the available metadata for every recommendation item.
public void onRecommendationResult( JSONArray jsonArray, String widgetID)
Parameters
- recommendation: An array of the recommended items returned by the sendRecommendationRequest call
- widgetID
Response Example
//full item metadata - each JSON object includes:
{
"item": {
"sku": "101",
"description": "JJ Supreme Basketball Shoes",
"url": "https://www.example.com/item/101",
"gender": "WOMENS",
"price": 100,
"image_url": " https://www.example.com/images/101.jpg",
"dy_item_type": "product",
"name": "JJ Basketball shoes"
},
"strId": 1,
"md": {}
}
}
//itemIDsOnly = true - each JSON object includes:
{
"item": {
"sku": "101"
},
"strId": 1,
"md": {}
}
}
Example
public void onRecommendationResult( JSONArray jsonArray, String widgetID )
{
// rendering the recommended items
}
Sets the current user’s affinity as response to explicit indication by the user. Returns YES if the input parameters are valid.
public boolean setRecommendationAffinities ( JSONObject affinities )
Parameter
- affinities: Key value pairs where the keys are product attributes and the value is an array of the attribute values
Example
JSONObject affinities = new JSONObject("{color:[“red”],style:[“loose”]}");
DYApi.getInstance().setRecommendationAffinities(affinities);
Reports a list of recommended items real impressions (i.e. were visible to user) within a given recommendation widget to the Dynamic Yield server. Returns YES if the input parameters are valid.
public boolean trackRecomItemRealImpression( String widgetID, String [] itemIDs )
Parameters
- widgetID: The recommendation widget ID used for receiving the recommendations items presented to the user
- itemIDs: An array of identifiers of recommendation items presented to the user
Example
String[] items = {"101", "102", “103”}
DYApi.getInstance().trackRecomItemRealImpression( “991”, items );
Reports the identifier of a recommended item tapped by the user within a given recommendation widget to the Dynamic Yield server. Returns YES if the input parameters are valid.
public boolean trackRecomItemClick( String widgetId, String itemId )
Parameters
- widgetId: The recommendation widget ID used for receiving the recommendations items presented to the user
- itemId: The identifier of a recommendation items tapped by the user
Example
DYApi.getInstance().trackRecomItemClick( “991”, “101” );
Additional Classes
A helper class storing the screen’s context attributes (e.g. required for recommendations).
public DYPageContext( String laguage, int type, JSONArray data )
Parameters
- language: The user’s locale in format. _ e.g. en_US or fr_CA
- type: The screen type from the following enum: DYPageContext.HOMEPAGE, DYPageContext.PRODUCT, DYPageContext.CATEGORY, DYPageContext.CART, DYPageContext.POST
- data: The specific data for the current page context
- For DYPageContext.HOMEPAGE: no context data
- For DYPageContext.CATEGORY: an array of all of the page’s categories, e.g. [“Mens”, “Tops”, …]
- For DYPageContext.PRODUCT: The SKU of the product displayed in the page, e.g. [“sku435-1a”]
- For DYPageContext.CART: an array of all the SKUs in the cart, e.g. [“sku435-1a”, “sku98123”]
- For DYPageContext.POST: The Post ID of the post displayed in the page, e.g. [“vid-3321-lng”]
- For DYPageContext.OTHER: no context data
-
For more details, see Page Context for Mobile.
Example
JSONArray data = new JSONArray();
data.put("101");
pageContext = new DYPageContext( "en_GB", DYPageContext.PRODUCT, data );
A helper class that filters the results of a recommendation request call, including and excluding products by their SKU or groupID
public DYRcomFilter(DYRcomFilterField field, DYRcomFilterType type, JSONArray value)
Parameters
- field: Must be either DY_FILTER_INCLUDE or DY_FILTER_EXCLUDE
- type: Must be either DY_FILTER_SKU or DY_FILTER_GROUP_ID
- value: An array of SKUs or groupIDs that define what is excluded or included.
Return Value
A DYRCOMFilter object
Example
JSONArray skus = new JSONArray();
skus.put("A1");
skus.put("A2");
DYRcomFilter filters = new DYRcomFilter(DYRcomFilterField.DY_FILTER_SKU, DYRcomFilterType.DY_FILTER_EXCLUDE,skus);
User Data
Class DYUserData is a helper class storing user profile attributes.
Returns all user data as a JSON object.
public org.json.JSONObject getUserData()
Example
DYUserData mUserData = new DYUserData();
JSONObject userData = mUserData.getUserData();
Sets the user’s email.
public void setEmail(java.lang.String email)
Parameter
- email: SHA 256 hashed email of the plain text email in lower case
Example
DYUserData userData = new DYUserData();
userData.setEmail(“18B258E9ADE091623DD829132E1E9D8B4A7F7D90ABEA194001C54341C3F27B79");
Sets the user’s external ID as maintained in other systems (e.g. CRM).
public void setExternalUserID(java.lang.String externalUserId)
Parameter
- externalUserId: The user’s unique ID as maintained in other systems
Deprecated Items
The items in this section are still supported but are being deprecated.
Chooses a Dynamic Content variation, returns the content as a JSON object, and reports an impression. If a user views the same variation more than once without calling the API again, call trackSmartObjectImpressions to report additional impressions. Call trackSmartObjectClicked every time a user clicks on a Dynamic Content variation created using the getSmartObjectData API to report a click.
public JSONObject getSmartObjectData(java.lang.String smartObjectID);
Parameter
- smartObjectID: The ID of the Dynamic Content campaign
Example Call
DYApi.getInstance().getSmartObjectData("Your_Dynamic_Content_ID");
Return Value
A JSON object that contains the following items:
- params : The JSON object with all variables and values (the content from the Variables tab in the user interface when creating variations)
- selectedVar – The content of the HTML, CSS, and JS tabs from the user interface combined into one string
Requires SDK version 2.6
Selects an image variation from the Dynamic Content defined in smartObjID and then assigns it to the imageview container defined in imageView. Returns true if the input parameters are valid. Note that Dynamic Content variations with HTML content will not be rendered.
If parameter fallBackURL is maintained, the image retrieved from the URL will be assigned to the imageView container in case no variation is returned from the Dynamic Yield server and in case the control group variation was selected.
Note: Since this is an API for Dynamic Content with image content, use the Dynamic Yield template “Mobile Image” in all Dynamic Content variations.
Important: In order to avoid empty content, it is mandatory to either use Dynamic Content in a webView with existing content or to use a fallbackURL
public void loadSmartObject( ImageView imageView, final String smartObjectId, final String defaultUrl );
Parameters
- imageView: The image container to which the Dynamic Content image content should be loaded to
- smartObjId: The Dynamic Content ID or name as maintained in the Dynamic Yield admin console
- fallBackURL: A URL to an image that should be loaded to the image view in case no Dynamic Content variation is returned from Dynamic Yield
Example
String fallbackURL = "https://www.example.com/Images/example.jpg";
ImageView mImageView = (ImageView)findViewById(R.id.imageView_so);
DYApi.getInstance().loadSmartObject( mImageView, smartObjId, fallbackURL );
Selects an HTML variation from the Dynamic Content defined in smartObjID and then assigns it to the webview container defined in webView. Returns true if the input parameters are valid. If parameter fallBackURL is maintained, the HTML content retrieved from the URL will be assigned to the webview container in case no variation is returned from the Dynamic Yield server and in case the control group variation was selected.
public void loadSmartObject( WebView webView, final String smartObjectId, final String defaultUrl );
Parameters
- webView: The webview to which the Dynamic Content variation HTML content should be assigned
- smartObjId: The Dynamic Content ID or name as maintained in the Dynamic Yield admin console)
- fallbackURL: A URL to the HTML content that should be loaded to the web view in case no Dynamic Content variation is returned from Dynamic Yield
Example
String fallbackURL = "https://www.example.com/Images/example.jpg";
WebView mWebView = (WebView)findViewById(R.id.webView_so);
DYApi.getInstance().loadSmartObject( mWebView, smartObjId, fallbackURL );
Returns the value assigned to a variable name specified in parameter varName. The value is maintained in Dynamic Yield’s admin console. If there is no value assigned, the value specified in parameter defaultValue will be used. Notice the value will be returned with type Object.
public java.lang.Object getSmartVariable(java.lang.String varName, java.lang.Object DefaultValue)
Parameters
- varName: The name of the variable as maintained in the Dynamic Yield Admin Console
- defaultValue: The value that should be assigned to the variable in case no value is returned (e.g. the variable has been archived or deleted in the Dynamic Yield admin console). The value can be null, but make sure that this does not negatively impact your app.
Example
(String) DYApi.getInstance().getSmartVariable("splashScreenText", "Welcome");
Sets the evaluator value, will remain valid until set again or until the session ends; returns Yes if input parameters are not nil or empty.
public boolean setEvaluator(String evaluatorID, JSONArray params, boolean saveBetweenSessions)
Requires SDK version 2.6.3
Parameters
- key: The evaluator ID from DY’s admin console
- params: Array of the evaluator value(s)
- saveBetweenSessions: true for saving the evaluator value between sessions, false to clear the value when a new session starts
Example
JSONArray values = new JSONArray("[\"winter\",\"sale\",\"women\"]");
DYApi.getInstance().setEvaluator("199", values, true);
Reports an application page view to the Dynamic Yield server; returns true if the uniqueID parameter is not null or empty.
public boolean trackPageView(java.lang.String uniqueID, DYPageContext context)
Parameters
- uniqueId: Unique identifier of the page as maintained in the application
- context: (Optional) The current screen’s context, for details see Page Context for Mobile.
Example
DYApi.getInstance().trackPageView("main_shopping_cart", context);
Reports an event to the Dynamic Yield server; returns true if eventName is not null or empty.
public boolean trackEvent(java.lang.String eventName, org.json.JSONObject properties)
Parameters
- eventName: The unique name of the event as maintained in the Dynamic Yield Admin console
- properties: Event properties JSON object containing key value pairs, keys the event properties are as maintained in the Dynamic Yield Admin console
Example
DYApi.getInstance().trackEvent("purchase", purchaseProps);
Returns an array of audiences to which to user is assigned from the Dynamic Yield server, or Null if no audience is available.
public String[] getUserAudiences()
Example
DYApi.getInstance().getUserAudiences();
Expose the user affinity profile.
public JSONObject getUserAffinityProfile()
Example
JSONObject userAffinity = DYApi.getInstance().getUserAffinityProfile();
Sets the API identifier in order to log the data to the correct Dynamic Yield account and site. Returns an instance of the class DYApi. This should be the first call to.
public static DYApi setContextAndSecret(android.content.Context context, java.lang.String secret)
Parameters
- context: The application context
- secret: String key, created in the Dynamic Yield admin console
Example
DYApi.setContextAndSecret(getApplication(),YOUR_SECRET_KEY);
Removed Items
The items in this section have been completely removed from our code.
Chooses a variation for a given experiment and returns information about the the variation, including the experiment variation name, id, and a JSON object containing all additional properties set in the Dynamic Yield admin console.
public org.json.JSONObject chooseVariationAndGetData(java.lang.Object expId)
Parameter
- expId: The experiment name or id
Example
DYApi.getInstance().chooseVariationAndGetData("Login screen experiments");
Chooses a variation for the given experiment id or name and returns the variation data in a JSON Object format (key/value pairs) from the Dynamic Yield server, regardless of previous results (e.g. also when variation is configured to be chosen once per session).
public org.json.JSONObject forceChooseVariationAndGetData(java.lang.Object expId)
Parameter
- expId: The experiment name or id
Example
DYApi.getInstance().forceChooseVariationAndGetData("Login screen experiments");
Forces the choosing of a specific variation for the given experiment.
public org.json.JSONArray getServerVariations(java.lang.Object expId
Parameters
- expId: The experiment name or id
- varId: The set variation name
Example
DYApi.getInstance().setVariation("Login screen experiments", "1");
Reports an application page view to the Dynamic Yield server; returns true if the uniqueID and name parameters are not null or empty.
public boolean trackPageView(java.lang.String uniqueID, java.lang.String name, java.lang.String section, DYPageContext context)
Parameters
- uniqueId: Unique identifier of the page as maintained in the application
- name: Display name of the page, will be used in the Dynamic Yield analytics reports
- section: (Optional) The section that hold the page – can be nil
- context: (Optional) The current screen’s context, for details see Page Context for Mobile.
Example
DYApi.getInstance().trackPageView("main_shopping_cart", "Shopping cart", "shopping", context);
Enables Dynamic Yield to automatically track page views whenever a new page is loaded. By default this is not enabled, meaning page views are tracked via an explicit API call.
public void setAutoPageViewsTracking(boolean enabled)
Parameter
- enabled: True will enable the implicit pave view tracking
Example
DYApi.getInstance().setAutoPageViewsTracking(true);
Sets the site variables sent with each event, these variables are sticky until clear method is triggered; returns true if siteVars is not null or empty.
public boolean setSiteVars(java.util.HashMap<java.lang.String,java.lang.String> siteVars)
Parameter
- siteVars: Hash map (key-value pairs) of the site variables; only variable names (keys) defined in the Dynamic Yield Admin Console are persisted
Example
HashMap<String, String > siteVars = new HashMap<String, String>(); siteVars.put("current day", getCurrentday());
DYApi.getInstance().setSiteVars(siteVars);
Clears the value of the site variable keys sent within the array names; returns true if names are not null or empty.
public boolean clearSiteVars(java.lang.String[] siteVarsNames)
Parameter
- names: Array of site variable names as maintained in the Dynamic Yield Admin Console
Example
DYApi.getInstance().clearSiteVars(clear);
Reports a list of unit impressions to the Dynamic Yield server; returns true if names is not null or empty.
public boolean trackUnitsImpression(java.lang.String[] names)
Parameter
- names: Array of unit names as maintained in the Dynamic Yield Admin Console
Example
DYApi.getInstance().trackUnitsImpression(new String[]{"sport","business news"});
Reports a unit tap (or click) by the user to the Dynamic Yield server; returns true if name is not null or empty.
public boolean trackUnitClicked(java.lang.String name)
Parameter
- names: The name of the clicked unit as maintained in the Dynamic Yield Admin Console
Example
DYApi.getInstance().trackUnitClicked("celebs");
This method is called when DY scripts are ready.
public void experimentsUpdatedAndReady();
initReply
Called after the server responded the initialization request
public void initReply(DYInitState reply);
Parameters
- reply: An enum holding the init state with the following possible values:
- NOT_INITIALIZED no server call has been made
- INIT_CALLED a server call has been sent
- INIT_FAILED the server can’t respond or an error has occurred
- SECTION_INACTIVE the section is inactive or the secret key is incorrect
- INIT_FINISHED the server call was successful
Example
@Override
public void initReply(DYInitState dyInitState) {
if (dyInitState == DYInitState.INIT_FINISHED) {
//..do something
}
}
Sets the evaluator value, will remain valid until set again or until the session ends; returns Yes if input parameters are not nil or empty.
public boolean setEvaluator(String key,java.util.JSONArray params)
Parameters
- key: The evaluator ID from DY’s admin console
- params: Array of the evaluator value(s)
Example
JSONArray values = new JSONArray("[\"winter\",\"sale\",\"women\"]");
DYApi.getInstance().setEvaluator("199", values);
This method is called just before the HTML Overlay content is rendered by Dynamic Yield and allows preventing its rendering. The default value is ‘true’.
public boolean shouldDYRender(String smartActionId);
Parameter
- smartActionId: The Smart Action ID as maintained in the Dynamic Yield Admin Console
Example
if (smartActionID.equals("Homepage campaign")) {
return false;
}