Android SDK - Quick Start Guide
Get up and running with the GetTranslated Android SDK in under 5 minutes! 🚀
Prerequisites
- Android API 21+ (Android 5.0)
- Java 11+
- A GetTranslated account and API key
- Create a project and use the CLI to translate your strings
- Call
GetTranslated.init(getApplicationContext(), "your-ck-api-key")in your Application class
That's it! The SDK automatically handles language detection, caching, and all other functionality. Language management, dynamic strings, user authentication, callbacks, and other features are optional and only needed if you want to customize the default behavior.
Step 1: Installation
Add the SDK from Maven Central to your app/build.gradle:
dependencies {
implementation 'ai.gettranslated:android-sdk:1.0.0'
}
Note: mavenCentral() is included by default in modern Android projects. If you need to add it manually, add to your build.gradle repositories block:
repositories {
google()
mavenCentral()
}
Step 2: Basic Setup
Initialize the SDK
Important: Initialize the SDK in your Application.onCreate() method, before any activities are created. This ensures that saved language preferences are applied before views are inflated, allowing Android resources to load in the correct language.
Add the initialization code to your Application class:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Initialize GetTranslated SDK with callback (recommended)
// Initialize in Application.onCreate() to ensure saved language preferences
// are applied before any activities are created
GetTranslated.init(getApplicationContext(), "your-ck-api-key", new GetTranslated.InitCallback() {
@Override
public void onInitSuccess() {
Log.d("GetTranslated", "SDK initialized successfully");
// SDK is ready to use
}
@Override
public void onInitError(int errorCode, String errorMessage) {
Log.e("GetTranslated", "Initialization failed: " + errorMessage);
// Handle initialization error
// errorCode: 401 (invalid API key), 403 (permission denied), 500 (server error), or 0 (network error)
}
});
}
}
- Always use
getApplicationContext()to prevent memory leaks - Using the callback version is recommended for better error handling
- Initialize in
Application.onCreate()before activities are created for proper language persistence
Add Internet Permission
Add to your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 3: Basic Translation
Simple Translation
// Get a translation (synchronous)
String translated = GetTranslated.getDynamicString("Hello, World!");
// Display in your UI
textView.setText(translated);
Translation with Callback
// Get a translation with callback (asynchronous)
GetTranslated.getDynamicString("Hello, World!", new GetTranslated.TranslationCallback() {
@Override
public void onTranslationReady(String translation) {
// Update UI on main thread
runOnUiThread(() -> {
textView.setText(translation);
});
}
@Override
public void onTranslationError(String errorMessage) {
// Handle error
Log.e("Translation", "Error: " + errorMessage);
}
});
Step 4: Language Management (Optional)
Note: This section is optional. The SDK automatically handles language detection and selection. You only need to read this if you want to implement a custom language selector or manually control language settings.
Automatic Language Detection
Important: The SDK automatically sets the application language during initialization based on:
- System preferences (device language)
- Saved user overrides (if previously set)
- Server language overrides (if provided)
You do not need to manually set the language unless you want to implement a custom language selector.
Manual Language Setting (Optional)
If you want to implement a language selector in your app, you can manually set the language:
// Optional: Only needed if implementing a language selector
GetTranslated.setLanguage("es"); // Spanish
GetTranslated.setLanguage("fr"); // French
// Note: Language changes are saved immediately, but may require an app restart
// or activity recreation to fully take effect for Android resources.
// Dynamic translations via getDynamicString() take effect immediately.
Get Supported Languages
// Get all supported languages
Set<String> languages = GetTranslated.getLanguages();
for (String lang : languages) {
Log.d("Language", "Supported: " + lang);
}
Get Current Language
// Get current device language
String currentLang = GetTranslated.getCurrentLanguage();
Log.d("Language", "Current: " + currentLang);
Check Initialization Status
// Check if SDK is initialized
boolean isInitialized = GetTranslated.isInitialized();
if (isInitialized) {
// SDK is ready to use
Set<String> languages = GetTranslated.getLanguages();
}
Note: If you initialize the SDK early (before views are created), you can check the initialization status after views are created to update your UI accordingly.
Step 5: User Management (Optional)
Note: This section is optional. The SDK automatically creates anonymous users by default. You only need to read this if you want to implement user authentication or track specific users.
Anonymous Users (Default)
The SDK automatically creates anonymous users when initialized without a user ID:
// Anonymous user (default)
GetTranslated.init(getApplicationContext(), "your-ck-api-key");
Authenticated Users
// Initialize with specific user ID
GetTranslated.init(getApplicationContext(), "your-ck-api-key", "user-123");
// Or login after initialization (with callback recommended)
GetTranslated.login("user-123", new GetTranslated.InitCallback() {
@Override
public void onInitSuccess() {
// Login successful - SDK re-initialized
// Supported languages are preserved
}
@Override
public void onInitError(int errorCode, String errorMessage) {
// Login re-initialization failed
Log.e("GetTranslated", "Login failed: " + errorMessage);
}
});
Logout
// Logout and return to anonymous user (with callback recommended)
GetTranslated.logout(new GetTranslated.InitCallback() {
@Override
public void onInitSuccess() {
// Logout successful - SDK re-initialized
// Supported languages are preserved
}
@Override
public void onInitError(int errorCode, String errorMessage) {
// Logout re-initialization failed
Log.e("GetTranslated", "Logout failed: " + errorMessage);
}
});
Step 6: Complete Example
Here's a complete MainActivity example:
public class MainActivity extends AppCompatActivity {
private static final String API_KEY = "your-ck-api-key";
private TextView translatedText;
private Button translateButton;
private Button languageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Apply saved language preference before inflating views
// This ensures Android resources load in the correct language
applySavedLanguagePreference();
setContentView(R.layout.activity_main);
// Initialize views
translatedText = findViewById(R.id.translatedText);
translateButton = findViewById(R.id.translateButton);
languageButton = findViewById(R.id.languageButton);
// Set up click listeners
translateButton.setOnClickListener(v -> translateText());
languageButton.setOnClickListener(v -> switchLanguage());
// Initialize SDK with callback
// Note: Full SDK initialization should ideally be done in Application.onCreate()
// This is shown here for demonstration, but Application-level init is preferred
GetTranslated.init(getApplicationContext(), API_KEY, new GetTranslated.InitCallback() {
@Override
public void onInitSuccess() {
Log.d("MainActivity", "SDK initialized successfully");
}
@Override
public void onInitError(int errorCode, String errorMessage) {
Log.e("MainActivity", "SDK initialization failed: " + errorMessage);
runOnUiThread(() -> {
Toast.makeText(MainActivity.this, "Failed to initialize translation service", Toast.LENGTH_SHORT).show();
});
}
});
}
/**
* Apply saved language preference before views are inflated.
* This allows Android resources to load in the correct language.
*/
private void applySavedLanguagePreference() {
try {
SharedPreferences prefs = getSharedPreferences(
ai.gettranslated.sdk.Constants.PREF_KEY, Context.MODE_PRIVATE);
String storedUserId = ai.gettranslated.sdk.StorageKeys.getStoredUserId(prefs);
if (storedUserId != null) {
String savedLang = ai.gettranslated.sdk.StorageKeys.getUserLanguageOverride(prefs, storedUserId);
if (savedLang != null && !savedLang.isEmpty()) {
Locale locale = Locale.forLanguageTag(savedLang);
Locale.setDefault(locale);
Configuration config = getResources().getConfiguration();
config.setLocale(locale);
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
}
}
} catch (Exception e) {
Log.e("MainActivity", "Failed to apply saved language", e);
}
}
private void translateText() {
String text = "Hello, World!";
GetTranslated.getDynamicString(text, new GetTranslated.TranslationCallback() {
@Override
public void onTranslationReady(String translation) {
runOnUiThread(() -> {
translatedText.setText(translation);
});
}
@Override
public void onTranslationError(String errorMessage) {
runOnUiThread(() -> {
translatedText.setText("Translation failed: " + errorMessage);
});
}
});
}
private void switchLanguage() {
// Toggle between English and Spanish
String currentLang = GetTranslated.getCurrentLanguage();
String newLang = "en".equals(currentLang) ? "es" : "en";
GetTranslated.setLanguage(newLang);
// Re-translate the text
translateText();
// Note: For Android resources to reflect the new language,
// you may need to recreate the activity or restart the app
// recreate(); // Uncomment to recreate activity immediately
// Note: For Android resources to reflect the new language,
// you may need to recreate the activity or restart the app
// recreate(); // Uncomment to recreate activity immediately
}
}
Step 7: Test Your Integration
- Run your app: Build and run on device or emulator
- Check the logs: Look for GetTranslated initialization messages
- Test translation: Tap the translate button
- Test language switching: Tap the language button
- Verify translations: Text should change between languages
Step 8: Add More Features
Logging Configuration
// Initialize with debug logging
GetTranslated.init(getApplicationContext(), "your-ck-api-key", null, Logger.LogLevel.DEBUG);
// Or configure logging separately
Logger.init(Logger.LogLevel.DEBUG, true, false);
Error Handling
GetTranslated.getDynamicString("Hello", new GetTranslated.TranslationCallback() {
@Override
public void onTranslationReady(String translation) {
// Success - update UI
textView.setText(translation);
}
@Override
public void onTranslationError(String errorMessage) {
// Error - show fallback or error message
textView.setText("Hello"); // Fallback to original text
Toast.makeText(context, "Translation failed", Toast.LENGTH_SHORT).show();
}
});
Common Issues & Solutions
❌ "Not initialized" error
Solution: Make sure to call GetTranslated.init() before using other methods. Use the callback version to ensure initialization completes before using the SDK. Also ensure your application is using the CLIENT SDK key.
❌ Translations not showing
Solution: Check that the SDK is initialized and the language is supported
❌ Network errors
Solution: Ensure internet permission is added and network is available
❌ Memory leaks
Solution: Always use getApplicationContext() instead of activity context
❌ Language not persisting after restart
Solution: Initialize the SDK in Application.onCreate() before activities are created, or apply saved language preference in Activity.onCreate() before setContentView(). This ensures Android resources load in the correct language.
❌ Language changes not taking effect
Solution: Language changes are saved immediately, but Android resources may require an activity restart or app restart to fully reflect the change. Dynamic translations via getDynamicString() take effect immediately. To see changes in Android resources immediately, recreate the activity with recreate() or restart the app.
Additional Options
Custom Logging
// Configure custom logging
Logger.init(Logger.LogLevel.VERBOSE, true, false);
// Use logger directly
Logger.logInfo("Custom message");
Logger.logError("Error occurred", exception);
Language Detection
// Get device language
String deviceLang = GetTranslated.getCurrentLanguage();
// Check if language is supported
Set<String> supported = GetTranslated.getLanguages();
boolean isSupported = supported.contains(deviceLang);