---
title: Using the Android SDK
description: >-
  Survicate allows you to launch precisely targeted surveys inside your app. In
  the Survicate Panel, you can set conditions that need to be met for the
  surveys to appear.
source_url:
  html: 'https://developers.survicate.com/mobile-sdk/android/using-sdk/'
  md: 'https://developers.survicate.com/mobile-sdk/android/using-sdk.md'
---
# Using the Android SDK

Survicate allows you to launch precisely targeted surveys inside your app. In the Survicate Panel, you can set conditions that need to be met for the surveys to appear. Users matching conditions defined in the Survicate panel will see the survey automatically. Here's a list of conditions you can use to target your surveys:

- Name of the screen that a user currently sees
- Any application event
- User attributes and identities
- Device language
- Operating system

Make sure to list all the screens and events described in your application. Once you got this covered, you or any person responsible for creating and managing surveys will be able to trigger surveys from the Survicate panel with no need for you to update the application.

**Warning**
Warning The SDK utilizes [SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences) to store information used by the targeting engine described in this section. Clearing SharedPreferences will cause the targeting system to malfunction; f.e. by showing the same survey twice to a single user.

## Targeting a survey by screen name

A survey can appear when a user is viewing a specific screen. For example, a survey can be triggered to show up on the application's home screen after a user spends more than ten seconds there. To set it up, you need to send information to Survicate about the user entering and leaving a screen.

_Note: Multiple active screens are allowed. In specific, calling enterScreen() does not make the previous screen to be discarded. Be sure to call leaveScreen() when you no longer want the screen to be treated as active._

```kotlin title="Kotlin"
// XML
class PurchaseSuccessActivity : Activity() {

    val SCREEN_NAME = "purchaseSuccess"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // ...
        Survicate.enterScreen(SCREEN_NAME)
    }

    override fun onDestroy() {
        super.onDestroy()
        Survicate.leaveScreen(SCREEN_NAME)
	}
}
```

```java title="Java"
public class PurchaseSuccessActivity extends Activity {

    public static final String SCREEN_KEY = "purchaseSuccess";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // ...
        Survicate.enterScreen(SCREEN_KEY);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        Survicate.leaveScreen(SCREEN_KEY);
    }

}
```

```kotlin title="Kotlin"
class PurchaseSuccessFragment : Fragment() {

    val SCREEN_NAME = "purchaseSuccess"

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // ...
        Survicate.enterScreen(SCREEN_NAME)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Survicate.leaveScreen(SCREEN_NAME)
	}
}
```

```java title="Java"
public class PurchaseSuccessFragment extends Fragment {

    public static final String SCREEN_KEY = "purchaseSuccess";

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // ...
        Survicate.enterScreen(SCREEN_KEY);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Survicate.leaveScreen(SCREEN_KEY);
    }
}
```

```kotlin title="Kotlin"
const val SCREEN_NAME = "purchaseSuccess"

@Composable
fun PurchaseSuccessScreen() {
    DisposableEffect(Unit) {
        Survicate.enterScreen(SCREEN_NAME)
        
        onDispose {
            Survicate.leaveScreen(SCREEN_NAME)
        }
    }
}
```

_Screen name is case sensitive. If there's any discrepancy between what's declared in the ‘Triggers’ tab of the Target section in the Survicate panel and the application code, the survey will not appear._

## Events-based survey targeting

Survicate Android SDK allows you to launch surveys based on events your users trigger in your app. Your survey will show instantly after an event occurs in your app.

```kotlin title="Kotlin"
// XML
button.setOnClickListener {
    // event without properties
    Survicate.invokeEvent("eventName")

    // event with properties
    val eventProperties = mapOf(
        "property1" to "value1",
        "property2" to "value2"
    )
    Survicate.invokeEvent("eventName", eventProperties)
}

// Jetpack Compose
Button(
    onClick = { 
        // Event without properties
        Survicate.invokeEvent("eventName")
        // Event with properties
        val eventProperties = mapOf(
            "property1" to "value1",
            "property2" to "value2"
        )
        Survicate.invokeEvent("eventName", eventProperties)
    }
) {
    Text("Click Me")
}
```

```java title="Java"
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // event without properties
        Survicate.invokeEvent("eventName");

        // event with properties
        Map<String, String> eventProperties = new HashMap<>();
        eventProperties.put("property1", "value1");
        eventProperties.put("property2", "value2");
        Survicate.invokeEvent("eventName", eventProperties);
    }
});
```

_Event name and property keys are case sensitive. If there is any discrepancy between what's declared in the ‘Triggers’ tab of the Target section in the Survicate panel and the application code, the survey will not appear._

## User identification & attributes

You can pass user attributes to Survicate as an additional layer of information about your users. Attributes can be used to:
* Identify respondents (by default survey responses are anonymous).
* Target surveys to specific users with Audience filters.
* Recall information in survey questions (e.g. include user name).
* Filter survey results.

```kotlin title="Kotlin"
// set a single trait
val trait = UserTrait("user_id", "YourUserID")
Survicate.setUserTrait(trait)

// or multiple traits at once
val textTrait = UserTrait("my_custom_attribute", "some value")
val numberTrait = UserTrait("age", 18)
val booleanTrait =  UserTrait("subscription_active", true)
val dateTrait = UserTrait("purchase_date", Date())

val traits = listOf(
    textTrait,
    numberTrait,
    booleanTrait,
    dateTrait
)
Survicate.setUserTraits(traits)
```

```java title="Java"
// set a single trait
UserTrait trait = new UserTrait("user_id", "YourUserID");
Survicate.setUserTrait(trait);

// or multiple traits at once
UserTrait textTrait = new UserTrait("my_custom_attribute", "some value");
UserTrait numberTrait = new UserTrait("age", 18);
UserTrait booleanTrait = new UserTrait("subscription_active", true);
UserTrait dateTrait = new UserTrait("purchase_date", new Date());

List<UserTrait> traits = Arrays.asList(
    textTrait,
    numberTrait,
    booleanTrait,
    dateTrait
);
Survicate.setUserTraits(traits);
```

_Bear in mind that user attributes are cached. You only need to provide them once, e.g. when user logs in, not after each `init()`. You can also change their values at any time to trigger a survey._

**Attribute types**

- **String**: any text, e.g. user name or e-mail.
- **Number**: an integer or decimal.
- **Boolean**: a logic value.
- **Date**: a `java.util.Date` that can be used in date or time interval filters (the latter measure elapsed time from a given timestamp).

**Special attributes**

- **user_id**: This corresponds to the "Logged-in status" in the panel's Audience filter. A user is considered logged-in when a trait with the "user_id" key has been set on the device, regardless of the value.

- **first_name**, **last_name**, **email**: If none of these is specified, a response will be marked as Anonymous in the panel.

**Additional notes**

- You can freely use custom attribute keys without the need to register them anywhere.

- In some panel functionalities (e.g. autocompletion), the attribute key will be available only after a survey response with the given attribute is uploaded (unless the key was added in the panel manually). By that time, the trait is saved only locally on the user's device.

- Note that the predefined attribute classes (`UserTrait.UserId`, `UserTrait.FirstName`, etc.) have been deprecated in version 4.0. Instead, you should use the `UserTrait(key, value)` constructor. You will find migration details in the deprecation messages.

## Response attributes

Response attributes are session-scoped attributes attached to survey responses. Unlike user attributes, they are cleared at the start of each new app session and are sent to Survicate along with the user's survey answers.

To update a response attribute, call the method again with the same name and a new value. To clear an attribute, pass an empty string as the value.

```kotlin title="Kotlin"
// set a single attribute
Survicate.setResponseAttribute(ResponseAttribute(name = "promo_code", value = "SAVE20"))

// or multiple attributes at once
val attributes = listOf(
    ResponseAttribute(name = "campaign_id", value = "summer-2024"),
    ResponseAttribute(name = "age", value = 18),
    ResponseAttribute(name = "subscription_active", value = true),
    ResponseAttribute(name = "trial_started_at", value = Date())
)
Survicate.setResponseAttributes(attributes)
```

```java title="Java"
// set a single attribute
Survicate.setResponseAttribute(new ResponseAttribute("promo_code", "SAVE20"));

// or multiple attributes at once
List<ResponseAttribute> attributes = Arrays.asList(
    new ResponseAttribute("campaign_id", "summer-2024"),
    new ResponseAttribute("age", 18),
    new ResponseAttribute("subscription_active", true),
    new ResponseAttribute("trial_started_at", new Date())
);
Survicate.setResponseAttributes(attributes);
```

`ResponseAttribute` accepts the following parameters:
- **name** (required): The key that identifies the attribute.
- **value** (required): The attribute value. Pass an empty string to clear an existing attribute.
- **provider** (optional): The name of the external service where this data comes from (e.g., "hubspot", "intercom"). This helps integrations identify and match your survey respondents with their profiles in that service.

**Attribute types**

- **String**: any text value.
- **Number**: an integer or decimal.
- **Boolean**: a logic value.
- **Date**: a `java.util.Date`.

## Setting the locale

Survicate SDK automatically detects the device locale using `Locale.getDefault()` and uses it both to choose the translation of a survey and to evaluate any Device language targeting filters.

If your app allows users to change the locale independently of the system settings, you can override the default by calling:

```kotlin title="Kotlin"
Survicate.setLocale(languageTag)
```

```java title="Java"
Survicate.setLocale(languageTag);
```

The argument must be a valid IETF language tag such as:

- A two‑letter ISO 639 code (e.g., "en", "fr")
- A three-letter code for languages without the two-letter equivalent (e.g., "haw", "yue")
- A language tag with region (e.g., "en-US", "pt-BR")

_Note: The specified locale setting applies only to the current application session. To preserve the preference after an app restart, make sure to call `setLocale(...)` again, anytime after `Survicate.init(...)`._

## Theme mode

When your survey has a theme with both light and dark modes, the SDK will select the proper variant following the system setting by default.

Optionally, you can enforce a specific theme mode with the `setThemeMode` method:

```kotlin title="Kotlin"
// LIGHT, DARK, or AUTO
Survicate.setThemeMode(ThemeMode.DARK)
```

```java title="Java"
// LIGHT, DARK, or AUTO
Survicate.setThemeMode(ThemeMode.DARK);
```

## Custom fonts

Using the `Survicate.setFonts` method you can specify custom fonts for survey presentation. You need to provide a font source for each font style required by the SDK.

```kotlin title="Kotlin"
val fontSystem = SurvicateFontSystem(
    regular = FontSource.ResId(R.font.my_font_regular),
    regularItalic = FontSource.ResId(R.font.my_font_regular_italic),
    bold = FontSource.ResId(R.font.my_font_bold),
    boldItalic = FontSource.ResId(R.font.my_font_bold_italic)
)
Survicate.setFonts(fontSystem)
```

```java title="Java"
SurvicateFontSystem fontSystem = new SurvicateFontSystem(
    /* regular */ new FontSource.ResId(R.font.my_font_regular),
    /* regularItalic */ new FontSource.ResId(R.font.my_font_regular_italic),
    /* bold */ new FontSource.ResId(R.font.my_font_bold),
    /* boldItalic */ new FontSource.ResId(R.font.my_font_bold_italic)
);
Survicate.setFonts(fontSystem);
```

The font can be provided by a resource ID or an asset path:
* `FontSource.ResId` - the Android resource ID of the font located in the `res/font` directory
* `FontSource.AssetPath` - the path to the font file relative to the `assets` directory (e.g. "fonts/MyFont.ttf")

## Event listeners

SDK allows you to utilize event listeners. You may find them useful to trigger actions in your application based on actions performed by respondents. Here's a list of events you can subscribe to:

* survey_displayed - occurs when survey is loaded and appears in the User Interface
* question_answered - occurs after a question is answered ( Survicate stores incomplete survey submissions )
* survey_closed - occurs when a user closes the survey using the close button
* survey_completed - occurs when a user finishes the survey

```kotlin title="Kotlin"
val listener = object : SurvicateEventListener() {
    override fun onSurveyDisplayed(event: SurveyDisplayedEvent) {
        Toast.makeText(this@MainActivity, "on survey displayed", Toast.LENGTH_SHORT).show()
    }
    override fun onQuestionAnswered(event: QuestionAnsweredEvent) {
        Toast.makeText(this@MainActivity, "on question answered", Toast.LENGTH_SHORT).show()
    }
    override fun onSurveyClosed(event: SurveyClosedEvent) {
        Toast.makeText(this@MainActivity, "on survey closed", Toast.LENGTH_SHORT).show()
    }
    override fun onSurveyCompleted(event: SurveyCompletedEvent) {
        Toast.makeText(this@MainActivity, "on survey completed", Toast.LENGTH_SHORT).show()
    }
}
Survicate.addEventListener(listener)
Survicate.removeEventListener(listener) // remember to remove the listener (e.g. in onDestroy)
```

```java title="Java"
SurvicateEventListener listener = new SurvicateEventListener() {
    @Override
    public void onSurveyDisplayed(@NonNull SurveyDisplayedEvent event) {
        Toast.makeText(MainActivity.this, "on survey displayed", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onQuestionAnswered(@NonNull QuestionAnsweredEvent event) {
        Toast.makeText(MainActivity.this, "on question answered", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onSurveyClosed(@NonNull SurveyClosedEvent event) {
        Toast.makeText(MainActivity.this, "on survey closed", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onSurveyCompleted(@NonNull SurveyCompletedEvent event) {
        Toast.makeText(MainActivity.this, "on survey completed", Toast.LENGTH_SHORT).show();
    }
};

Survicate.addEventListener(listener);
Survicate.removeEventListener(listener); // remember to remove the listener (e.g. in onDestroy)
```

_Deprecation note: The `Survicate.setEventListener` method has been deprecated since version 4.1.0. You should use the `addEventListener` and `removeEventListener` methods instead._

**SurvicateAnswer properties (`QuestionAnsweredEvent.answer`)**

| Property | Type      | Description                                                                                    |
|:---------|:----------|:-----------------------------------------------------------------------------------------------|
| type     | String    | Answer type. One of: ['text', 'single', 'multiple', 'smiley_scale', 'rating', 'csat', 'numerical_scale', 'nps', 'date', 'form', 'matrix', 'button_close', 'button_next', 'button_link']. |
| id       | Long?   | Answer ID. **Applicable only for types: ['single', 'smiley_scale', 'csat', 'rating', 'numerical_scale'].** |
| ids      | Set&lt;Long&gt;? | Selected answer IDs. **Applicable only for type = ['multiple'].** |
| value    | String?    | Text representation of an answer, e.g. "Happy" for smiley scale. A `null` value in case of a skipped question. **Not applicable for call-to-action answers: ['button_close', 'button_next', 'button_link'].** |

_The `id`, `ids` and `value` properties are provided only for the cases enlisted in the table above. Therefore, expect that there might be answer objects that consist only of the `type` property._

## Reseting user data for testing purposes

If you need to test surveys on your device, the `reset()` method can be useful. It clears all user data stored on the device — including survey views, attributes, and information about answered surveys — as well as the current in-memory state of the SDK.

```kotlin title="Kotlin"
Survicate.reset()
```

```java title="Java"
Survicate.reset();
```
