diff --git a/admob/build.gradle b/admob/build.gradle index 0145c30c5..87591c53d 100644 --- a/admob/build.gradle +++ b/admob/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/analytics/app/src/main/java/com/google/firebase/example/analytics/kotlin/MainActivity.kt b/analytics/app/src/main/java/com/google/firebase/example/analytics/kotlin/MainActivity.kt index bf08f6e47..3cee987ea 100644 --- a/analytics/app/src/main/java/com/google/firebase/example/analytics/kotlin/MainActivity.kt +++ b/analytics/app/src/main/java/com/google/firebase/example/analytics/kotlin/MainActivity.kt @@ -92,7 +92,7 @@ class MainActivity : param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "Related products") param( FirebaseAnalytics.Param.ITEMS, - arrayOf(itemJeggingsWithIndex, itemBootsWithIndex, itemSocksWithIndex) + arrayOf(itemJeggingsWithIndex, itemBootsWithIndex, itemSocksWithIndex), ) } // [END view_item_list] diff --git a/analytics/build.gradle b/analytics/build.gradle index 302b37ca8..079fc78ec 100644 --- a/analytics/build.gradle +++ b/analytics/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/appcheck/app/build.gradle b/appcheck/app/build.gradle index 6b6fb423d..97f3a69da 100644 --- a/appcheck/app/build.gradle +++ b/appcheck/app/build.gradle @@ -36,7 +36,7 @@ dependencies { implementation 'com.google.android.material:material:1.8.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' - implementation 'com.google.firebase:firebase-appcheck:16.1.2' + implementation 'com.google.firebase:firebase-appcheck-ktx:16.1.2' implementation 'com.google.firebase:firebase-appcheck-debug:16.1.2' implementation 'com.google.firebase:firebase-appcheck-playintegrity:16.1.2' diff --git a/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/ApiWithAppCheckExample.kt b/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/ApiWithAppCheckExample.kt index dd49a8bb1..49edade0a 100644 --- a/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/ApiWithAppCheckExample.kt +++ b/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/ApiWithAppCheckExample.kt @@ -6,13 +6,12 @@ import retrofit2.Retrofit import retrofit2.http.GET import retrofit2.http.Header - // [START appcheck_custom_backend] class ApiWithAppCheckExample { interface YourExampleBackendService { @GET("yourExampleEndpoint") fun exampleData( - @Header("X-Firebase-AppCheck") appCheckToken: String + @Header("X-Firebase-AppCheck") appCheckToken: String, ): Call> } diff --git a/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/CustomProvider.kt b/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/CustomProvider.kt index 98fbcdfa4..3c265dbcc 100644 --- a/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/CustomProvider.kt +++ b/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/CustomProvider.kt @@ -8,12 +8,14 @@ import com.google.firebase.appcheck.AppCheckProvider import com.google.firebase.appcheck.AppCheckProviderFactory import com.google.firebase.appcheck.AppCheckToken import com.google.firebase.appcheck.FirebaseAppCheck +import com.google.firebase.ktx.Firebase +import com.google.firebase.ktx.initialize class CustomProvider { // [START appcheck_custom_provider] class YourCustomAppCheckToken( private val token: String, - private val expiration: Long + private val expiration: Long, ) : AppCheckToken() { override fun getToken(): String = token override fun getExpireTimeMillis(): Long = expiration @@ -49,11 +51,11 @@ class CustomProvider { private fun init(context: Context) { // [START appcheck_initialize_custom_provider] - FirebaseApp.initializeApp(/*context=*/ context) + Firebase.initialize(context) val firebaseAppCheck = FirebaseAppCheck.getInstance() firebaseAppCheck.installAppCheckProviderFactory( - YourCustomAppCheckProviderFactory() + YourCustomAppCheckProviderFactory(), ) // [END appcheck_initialize_custom_provider] } -} \ No newline at end of file +} diff --git a/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/MainActivity.kt b/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/MainActivity.kt index 5e193a37a..a0be121a2 100644 --- a/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/MainActivity.kt +++ b/appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/MainActivity.kt @@ -2,12 +2,12 @@ package com.google.firebase.example.appcheck.kotlin import android.os.Bundle import androidx.appcompat.app.AppCompatActivity -import com.google.firebase.FirebaseApp import com.google.firebase.appcheck.FirebaseAppCheck import com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory import com.google.firebase.appcheck.playintegrity.PlayIntegrityAppCheckProviderFactory import com.google.firebase.example.appcheck.R - +import com.google.firebase.ktx.Firebase +import com.google.firebase.ktx.initialize class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { @@ -17,21 +17,21 @@ class MainActivity : AppCompatActivity() { private fun init() { // [START appcheck_initialize] - FirebaseApp.initializeApp(/*context=*/this) + Firebase.initialize(context = this) val firebaseAppCheck = FirebaseAppCheck.getInstance() firebaseAppCheck.installAppCheckProviderFactory( - PlayIntegrityAppCheckProviderFactory.getInstance() + PlayIntegrityAppCheckProviderFactory.getInstance(), ) // [END appcheck_initialize] } private fun initDebug() { // [START appcheck_initialize_debug] - FirebaseApp.initializeApp(/*context=*/this) + Firebase.initialize(context = this) val firebaseAppCheck = FirebaseAppCheck.getInstance() firebaseAppCheck.installAppCheckProviderFactory( - DebugAppCheckProviderFactory.getInstance() + DebugAppCheckProviderFactory.getInstance(), ) // [END appcheck_initialize_debug] } -} \ No newline at end of file +} diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/AnonymousAuthActivity.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/AnonymousAuthActivity.kt index a883e1c00..82b662877 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/AnonymousAuthActivity.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/AnonymousAuthActivity.kt @@ -39,20 +39,23 @@ class AnonymousAuthActivity : Activity() { private fun signInAnonymously() { // [START signin_anonymously] auth.signInAnonymously() - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - // Sign in success, update UI with the signed-in user's information - Log.d(TAG, "signInAnonymously:success") - val user = auth.currentUser - updateUI(user) - } else { - // If sign in fails, display a message to the user. - Log.w(TAG, "signInAnonymously:failure", task.exception) - Toast.makeText(baseContext, "Authentication failed.", - Toast.LENGTH_SHORT).show() - updateUI(null) - } + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Sign in success, update UI with the signed-in user's information + Log.d(TAG, "signInAnonymously:success") + val user = auth.currentUser + updateUI(user) + } else { + // If sign in fails, display a message to the user. + Log.w(TAG, "signInAnonymously:failure", task.exception) + Toast.makeText( + baseContext, + "Authentication failed.", + Toast.LENGTH_SHORT, + ).show() + updateUI(null) } + } // [END signin_anonymously] } @@ -61,23 +64,25 @@ class AnonymousAuthActivity : Activity() { val credential = EmailAuthProvider.getCredential("", "") // [START link_credential] auth.currentUser!!.linkWithCredential(credential) - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - Log.d(TAG, "linkWithCredential:success") - val user = task.result?.user - updateUI(user) - } else { - Log.w(TAG, "linkWithCredential:failure", task.exception) - Toast.makeText(baseContext, "Authentication failed.", - Toast.LENGTH_SHORT).show() - updateUI(null) - } + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + Log.d(TAG, "linkWithCredential:success") + val user = task.result?.user + updateUI(user) + } else { + Log.w(TAG, "linkWithCredential:failure", task.exception) + Toast.makeText( + baseContext, + "Authentication failed.", + Toast.LENGTH_SHORT, + ).show() + updateUI(null) } + } // [END link_credential] } private fun updateUI(user: FirebaseUser?) { - } companion object { diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt index 028477f91..1018944ad 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt @@ -43,26 +43,28 @@ class CustomAuthActivity : Activity() { // [START sign_in_custom] customToken?.let { auth.signInWithCustomToken(it) - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - // Sign in success, update UI with the signed-in user's information - Log.d(TAG, "signInWithCustomToken:success") - val user = auth.currentUser - updateUI(user) - } else { - // If sign in fails, display a message to the user. - Log.w(TAG, "signInWithCustomToken:failure", task.exception) - Toast.makeText(baseContext, "Authentication failed.", - Toast.LENGTH_SHORT).show() - updateUI(null) - } + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Sign in success, update UI with the signed-in user's information + Log.d(TAG, "signInWithCustomToken:success") + val user = auth.currentUser + updateUI(user) + } else { + // If sign in fails, display a message to the user. + Log.w(TAG, "signInWithCustomToken:failure", task.exception) + Toast.makeText( + baseContext, + "Authentication failed.", + Toast.LENGTH_SHORT, + ).show() + updateUI(null) } + } } // [END sign_in_custom] } private fun updateUI(user: FirebaseUser?) { - } companion object { diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/EmailPasswordActivity.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/EmailPasswordActivity.kt index f1f21fe90..ab2c58cbe 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/EmailPasswordActivity.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/EmailPasswordActivity.kt @@ -15,7 +15,6 @@ class EmailPasswordActivity : Activity() { private lateinit var auth: FirebaseAuth // [END declare_auth] - public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -30,7 +29,7 @@ class EmailPasswordActivity : Activity() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser - if(currentUser != null){ + if (currentUser != null) { reload() } } @@ -39,40 +38,46 @@ class EmailPasswordActivity : Activity() { private fun createAccount(email: String, password: String) { // [START create_user_with_email] auth.createUserWithEmailAndPassword(email, password) - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - // Sign in success, update UI with the signed-in user's information - Log.d(TAG, "createUserWithEmail:success") - val user = auth.currentUser - updateUI(user) - } else { - // If sign in fails, display a message to the user. - Log.w(TAG, "createUserWithEmail:failure", task.exception) - Toast.makeText(baseContext, "Authentication failed.", - Toast.LENGTH_SHORT).show() - updateUI(null) - } + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Sign in success, update UI with the signed-in user's information + Log.d(TAG, "createUserWithEmail:success") + val user = auth.currentUser + updateUI(user) + } else { + // If sign in fails, display a message to the user. + Log.w(TAG, "createUserWithEmail:failure", task.exception) + Toast.makeText( + baseContext, + "Authentication failed.", + Toast.LENGTH_SHORT, + ).show() + updateUI(null) } + } // [END create_user_with_email] } private fun signIn(email: String, password: String) { // [START sign_in_with_email] auth.signInWithEmailAndPassword(email, password) - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - // Sign in success, update UI with the signed-in user's information - Log.d(TAG, "signInWithEmail:success") - val user = auth.currentUser - updateUI(user) - } else { - // If sign in fails, display a message to the user. - Log.w(TAG, "signInWithEmail:failure", task.exception) - Toast.makeText(baseContext, "Authentication failed.", - Toast.LENGTH_SHORT).show() - updateUI(null) - } + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Sign in success, update UI with the signed-in user's information + Log.d(TAG, "signInWithEmail:success") + val user = auth.currentUser + updateUI(user) + } else { + // If sign in fails, display a message to the user. + Log.w(TAG, "signInWithEmail:failure", task.exception) + Toast.makeText( + baseContext, + "Authentication failed.", + Toast.LENGTH_SHORT, + ).show() + updateUI(null) } + } // [END sign_in_with_email] } @@ -80,18 +85,16 @@ class EmailPasswordActivity : Activity() { // [START send_email_verification] val user = auth.currentUser!! user.sendEmailVerification() - .addOnCompleteListener(this) { task -> - // Email Verification sent - } + .addOnCompleteListener(this) { task -> + // Email Verification sent + } // [END send_email_verification] } private fun updateUI(user: FirebaseUser?) { - } private fun reload() { - } companion object { diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/EmulatorSuite.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/EmulatorSuite.kt index 44677e58d..06c2ad1fd 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/EmulatorSuite.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/EmulatorSuite.kt @@ -12,5 +12,4 @@ class EmulatorSuite { Firebase.auth.useEmulator("10.0.2.2", 9099) // [END auth_emulator_connect] } - -} \ No newline at end of file +} diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FacebookLoginActivity.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FacebookLoginActivity.kt index f8d677048..729b4c0b5 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FacebookLoginActivity.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FacebookLoginActivity.kt @@ -36,26 +36,28 @@ class FacebookLoginActivity : Activity() { auth = Firebase.auth // [END initialize_auth] - // [START initialize_fblogin] // Initialize Facebook Login button callbackManager = CallbackManager.Factory.create() buttonFacebookLogin.setReadPermissions("email", "public_profile") - buttonFacebookLogin.registerCallback(callbackManager, object : FacebookCallback { - override fun onSuccess(loginResult: LoginResult) { - Log.d(TAG, "facebook:onSuccess:$loginResult") - handleFacebookAccessToken(loginResult.accessToken) - } + buttonFacebookLogin.registerCallback( + callbackManager, + object : FacebookCallback { + override fun onSuccess(loginResult: LoginResult) { + Log.d(TAG, "facebook:onSuccess:$loginResult") + handleFacebookAccessToken(loginResult.accessToken) + } - override fun onCancel() { - Log.d(TAG, "facebook:onCancel") - } + override fun onCancel() { + Log.d(TAG, "facebook:onCancel") + } - override fun onError(error: FacebookException) { - Log.d(TAG, "facebook:onError", error) - } - }) + override fun onError(error: FacebookException) { + Log.d(TAG, "facebook:onError", error) + } + }, + ) // [END initialize_fblogin] } @@ -83,25 +85,27 @@ class FacebookLoginActivity : Activity() { val credential = FacebookAuthProvider.getCredential(token.token) auth.signInWithCredential(credential) - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - // Sign in success, update UI with the signed-in user's information - Log.d(TAG, "signInWithCredential:success") - val user = auth.currentUser - updateUI(user) - } else { - // If sign in fails, display a message to the user. - Log.w(TAG, "signInWithCredential:failure", task.exception) - Toast.makeText(baseContext, "Authentication failed.", - Toast.LENGTH_SHORT).show() - updateUI(null) - } + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Sign in success, update UI with the signed-in user's information + Log.d(TAG, "signInWithCredential:success") + val user = auth.currentUser + updateUI(user) + } else { + // If sign in fails, display a message to the user. + Log.w(TAG, "signInWithCredential:failure", task.exception) + Toast.makeText( + baseContext, + "Authentication failed.", + Toast.LENGTH_SHORT, + ).show() + updateUI(null) } + } } // [END auth_with_facebook] private fun updateUI(user: FirebaseUser?) { - } companion object { diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FirebaseUIActivity.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FirebaseUIActivity.kt index 4a83347b9..a009c2200 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FirebaseUIActivity.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FirebaseUIActivity.kt @@ -7,7 +7,6 @@ import com.firebase.ui.auth.AuthUI.IdpConfig import com.firebase.ui.auth.AuthUI.IdpConfig.EmailBuilder import com.firebase.ui.auth.FirebaseAuthUIActivityResultContract import com.firebase.ui.auth.data.model.FirebaseAuthUIAuthenticationResult -import com.firebase.ui.auth.util.ExtraConstants import com.google.firebase.auth.ActionCodeSettings import com.google.firebase.auth.FirebaseAuth import com.google.firebase.quickstart.auth.R @@ -17,7 +16,7 @@ abstract class FirebaseUIActivity : AppCompatActivity() { // [START auth_fui_create_launcher] // See: https://developer.android.com/training/basics/intents/result private val signInLauncher = registerForActivityResult( - FirebaseAuthUIActivityResultContract() + FirebaseAuthUIActivityResultContract(), ) { res -> this.onSignInResult(res) } @@ -32,17 +31,18 @@ abstract class FirebaseUIActivity : AppCompatActivity() { // [START auth_fui_create_intent] // Choose authentication providers val providers = arrayListOf( - AuthUI.IdpConfig.EmailBuilder().build(), - AuthUI.IdpConfig.PhoneBuilder().build(), - AuthUI.IdpConfig.GoogleBuilder().build(), - AuthUI.IdpConfig.FacebookBuilder().build(), - AuthUI.IdpConfig.TwitterBuilder().build()) + AuthUI.IdpConfig.EmailBuilder().build(), + AuthUI.IdpConfig.PhoneBuilder().build(), + AuthUI.IdpConfig.GoogleBuilder().build(), + AuthUI.IdpConfig.FacebookBuilder().build(), + AuthUI.IdpConfig.TwitterBuilder().build(), + ) // Create and launch sign-in intent val signInIntent = AuthUI.getInstance() - .createSignInIntentBuilder() - .setAvailableProviders(providers) - .build() + .createSignInIntentBuilder() + .setAvailableProviders(providers) + .build() signInLauncher.launch(signInIntent) // [END auth_fui_create_intent] } @@ -66,20 +66,20 @@ abstract class FirebaseUIActivity : AppCompatActivity() { private fun signOut() { // [START auth_fui_signout] AuthUI.getInstance() - .signOut(this) - .addOnCompleteListener { - // ... - } + .signOut(this) + .addOnCompleteListener { + // ... + } // [END auth_fui_signout] } private fun delete() { // [START auth_fui_delete] AuthUI.getInstance() - .delete(this) - .addOnCompleteListener { - // ... - } + .delete(this) + .addOnCompleteListener { + // ... + } // [END auth_fui_delete] } @@ -88,11 +88,11 @@ abstract class FirebaseUIActivity : AppCompatActivity() { // [START auth_fui_theme_logo] val signInIntent = AuthUI.getInstance() - .createSignInIntentBuilder() - .setAvailableProviders(providers) - .setLogo(R.drawable.my_great_logo) // Set logo drawable - .setTheme(R.style.MySuperAppTheme) // Set theme - .build() + .createSignInIntentBuilder() + .setAvailableProviders(providers) + .setLogo(R.drawable.my_great_logo) // Set logo drawable + .setTheme(R.style.MySuperAppTheme) // Set theme + .build() signInLauncher.launch(signInIntent) // [END auth_fui_theme_logo] } @@ -101,12 +101,13 @@ abstract class FirebaseUIActivity : AppCompatActivity() { val providers = emptyList() // [START auth_fui_pp_tos] val signInIntent = AuthUI.getInstance() - .createSignInIntentBuilder() - .setAvailableProviders(providers) - .setTosAndPrivacyPolicyUrls( - "https://example.com/terms.html", - "https://example.com/privacy.html") - .build() + .createSignInIntentBuilder() + .setAvailableProviders(providers) + .setTosAndPrivacyPolicyUrls( + "https://example.com/terms.html", + "https://example.com/privacy.html", + ) + .build() signInLauncher.launch(signInIntent) // [END auth_fui_pp_tos] } @@ -114,24 +115,25 @@ abstract class FirebaseUIActivity : AppCompatActivity() { open fun emailLink() { // [START auth_fui_email_link] val actionCodeSettings = ActionCodeSettings.newBuilder() - .setAndroidPackageName( /* yourPackageName= */ - "...", /* installIfNotAvailable= */ - true, /* minimumVersion= */ - null) - .setHandleCodeInApp(true) // This must be set to true - .setUrl("https://google.com") // This URL needs to be whitelisted - .build() + .setAndroidPackageName( // yourPackageName= + "...", // installIfNotAvailable= + true, // minimumVersion= + null, + ) + .setHandleCodeInApp(true) // This must be set to true + .setUrl("https://google.com") // This URL needs to be whitelisted + .build() val providers = listOf( - EmailBuilder() - .enableEmailLinkSignIn() - .setActionCodeSettings(actionCodeSettings) - .build() + EmailBuilder() + .enableEmailLinkSignIn() + .setActionCodeSettings(actionCodeSettings) + .build(), ) val signInIntent = AuthUI.getInstance() - .createSignInIntentBuilder() - .setAvailableProviders(providers) - .build() + .createSignInIntentBuilder() + .setAvailableProviders(providers) + .build() signInLauncher.launch(signInIntent) // [END auth_fui_email_link] } @@ -145,10 +147,10 @@ abstract class FirebaseUIActivity : AppCompatActivity() { val link = extras.getString("email_link_sign_in") if (link != null) { val signInIntent = AuthUI.getInstance() - .createSignInIntentBuilder() - .setEmailLink(link) - .setAvailableProviders(providers) - .build() + .createSignInIntentBuilder() + .setEmailLink(link) + .setAvailableProviders(providers) + .build() signInLauncher.launch(signInIntent) } } diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GenericIdpActivity.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GenericIdpActivity.kt index c191f97f2..bb6407a36 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GenericIdpActivity.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GenericIdpActivity.kt @@ -11,6 +11,14 @@ class GenericIdpActivity : AppCompatActivity() { private lateinit var firebaseAuth: FirebaseAuth + /** + * Used to improve readability of snippets that take an Activity as + * argument. + * Eg: `startActivityForSignInWithProvider(activity)` reads better than + * `startActivityForSignInWithProvider(this)` + */ + private val activity = this + fun twitter() { // [START auth_twitter_provider_create] val provider = OAuthProvider.newBuilder("twitter.com") @@ -73,7 +81,6 @@ class GenericIdpActivity : AppCompatActivity() { val provider = OAuthProvider.newBuilder("yahoo.com") // [END auth_yahoo_provider_create] - // [START auth_yahoo_provider_params] // Prompt user to re-authenticate to Yahoo. provider.addCustomParameter("prompt", "login") @@ -82,7 +89,6 @@ class GenericIdpActivity : AppCompatActivity() { provider.addCustomParameter("language", "fr") // [END auth_yahoo_provider_params] - // [START auth_yahoo_provider_scopes] // Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. @@ -95,13 +101,11 @@ class GenericIdpActivity : AppCompatActivity() { val providerBuilder = OAuthProvider.newBuilder("oidc.example-provider") // [END auth_oidc_provider_create] - // [START auth_oidc_provider_params] // Target specific email with login hint. providerBuilder.addCustomParameter("login_hint", "user@example.com") // [END auth_oidc_provider_params] - // [START auth_oidc_provider_scopes] // Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. @@ -137,7 +141,7 @@ class GenericIdpActivity : AppCompatActivity() { fun signInWithProvider(provider: OAuthProvider.Builder) { // [START auth_oidc_provider_signin] firebaseAuth - .startActivityForSignInWithProvider( /* activity = */this, provider.build()) + .startActivityForSignInWithProvider(activity, provider.build()) .addOnSuccessListener { // User is signed in. // IdP data available in @@ -158,7 +162,7 @@ class GenericIdpActivity : AppCompatActivity() { // The user is already signed-in. val firebaseUser = firebaseAuth.currentUser!! firebaseUser - .startActivityForLinkWithProvider( /* activity = */this, provider.build()) + .startActivityForLinkWithProvider(activity, provider.build()) .addOnSuccessListener { // Provider credential is linked to the current user. // IdP data available in @@ -179,7 +183,7 @@ class GenericIdpActivity : AppCompatActivity() { // The user is already signed-in. val firebaseUser = firebaseAuth.currentUser!! firebaseUser - .startActivityForReauthenticateWithProvider( /* activity = */this, provider.build()) + .startActivityForReauthenticateWithProvider(activity, provider.build()) .addOnSuccessListener { // User is re-authenticated with fresh tokens and // should be able to perform sensitive operations @@ -211,4 +215,4 @@ class GenericIdpActivity : AppCompatActivity() { } // [END auth_oidc_provider_signin_manual] } -} \ No newline at end of file +} diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GoogleSignInActivity.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GoogleSignInActivity.kt index 1d900e452..2ab7a44e1 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GoogleSignInActivity.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GoogleSignInActivity.kt @@ -32,14 +32,13 @@ class GoogleSignInActivity : Activity() { // [START config_signin] // Configure Google Sign In val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) - .requestIdToken(getString(R.string.default_web_client_id)) - .requestEmail() - .build() + .requestIdToken(getString(R.string.default_web_client_id)) + .requestEmail() + .build() googleSignInClient = GoogleSignIn.getClient(this, gso) // [END config_signin] - // [START initialize_auth] // Initialize Firebase Auth auth = Firebase.auth @@ -79,18 +78,18 @@ class GoogleSignInActivity : Activity() { private fun firebaseAuthWithGoogle(idToken: String) { val credential = GoogleAuthProvider.getCredential(idToken, null) auth.signInWithCredential(credential) - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - // Sign in success, update UI with the signed-in user's information - Log.d(TAG, "signInWithCredential:success") - val user = auth.currentUser - updateUI(user) - } else { - // If sign in fails, display a message to the user. - Log.w(TAG, "signInWithCredential:failure", task.exception) - updateUI(null) - } + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Sign in success, update UI with the signed-in user's information + Log.d(TAG, "signInWithCredential:success") + val user = auth.currentUser + updateUI(user) + } else { + // If sign in fails, display a message to the user. + Log.w(TAG, "signInWithCredential:failure", task.exception) + updateUI(null) } + } } // [END auth_with_google] @@ -102,7 +101,6 @@ class GoogleSignInActivity : Activity() { // [END signin] private fun updateUI(user: FirebaseUser?) { - } companion object { diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MainActivity.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MainActivity.kt index 2f3ccb02c..97d5ac62e 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MainActivity.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MainActivity.kt @@ -100,11 +100,11 @@ abstract class MainActivity : AppCompatActivity() { } user!!.updateProfile(profileUpdates) - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Log.d(TAG, "User profile updated.") - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Log.d(TAG, "User profile updated.") } + } // [END update_profile] } @@ -113,11 +113,11 @@ abstract class MainActivity : AppCompatActivity() { val user = Firebase.auth.currentUser user!!.updateEmail("user@example.com") - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Log.d(TAG, "User email address updated.") - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Log.d(TAG, "User email address updated.") } + } // [END update_email] } @@ -127,11 +127,11 @@ abstract class MainActivity : AppCompatActivity() { val newPassword = "SOME-SECURE-PASSWORD" user!!.updatePassword(newPassword) - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Log.d(TAG, "User password updated.") - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Log.d(TAG, "User password updated.") } + } // [END update_password] } @@ -140,11 +140,11 @@ abstract class MainActivity : AppCompatActivity() { val user = Firebase.auth.currentUser user!!.sendEmailVerification() - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Log.d(TAG, "Email sent.") - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Log.d(TAG, "Email sent.") } + } // [END send_email_verification] } @@ -155,18 +155,18 @@ abstract class MainActivity : AppCompatActivity() { val url = "http://www.example.com/verify?uid=" + user.uid val actionCodeSettings = ActionCodeSettings.newBuilder() - .setUrl(url) - .setIOSBundleId("com.example.ios") - // The default for this is populated with the current android package name. - .setAndroidPackageName("com.example.android", false, null) - .build() + .setUrl(url) + .setIOSBundleId("com.example.ios") + // The default for this is populated with the current android package name. + .setAndroidPackageName("com.example.android", false, null) + .build() user.sendEmailVerification(actionCodeSettings) - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Log.d(TAG, "Email sent.") - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Log.d(TAG, "Email sent.") } + } // [END send_email_verification_with_continue_url] // [START localize_verification_email] @@ -181,11 +181,11 @@ abstract class MainActivity : AppCompatActivity() { val emailAddress = "user@example.com" Firebase.auth.sendPasswordResetEmail(emailAddress) - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Log.d(TAG, "Email sent.") - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Log.d(TAG, "Email sent.") } + } // [END send_password_reset] } @@ -194,11 +194,11 @@ abstract class MainActivity : AppCompatActivity() { val user = Firebase.auth.currentUser!! user.delete() - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Log.d(TAG, "User account deleted.") - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Log.d(TAG, "User account deleted.") } + } // [END delete_user] } @@ -210,34 +210,36 @@ abstract class MainActivity : AppCompatActivity() { // email and password credentials but there are multiple possible providers, // such as GoogleAuthProvider or FacebookAuthProvider. val credential = EmailAuthProvider - .getCredential("user@example.com", "password1234") + .getCredential("user@example.com", "password1234") // Prompt the user to re-provide their sign-in credentials user.reauthenticate(credential) - .addOnCompleteListener { Log.d(TAG, "User re-authenticated.") } + .addOnCompleteListener { Log.d(TAG, "User re-authenticated.") } // [END reauthenticate] } private fun authWithGithub() { - // [START auth_with_github] val token = "" val credential = GithubAuthProvider.getCredential(token) Firebase.auth.signInWithCredential(credential) - .addOnCompleteListener(this) { task -> - Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful) - - // If sign in fails, display a message to the user. If sign in succeeds - // the auth state listener will be notified and logic to handle the - // signed in user can be handled in the listener. - if (!task.isSuccessful) { - Log.w(TAG, "signInWithCredential", task.exception) - Toast.makeText(baseContext, "Authentication failed.", - Toast.LENGTH_SHORT).show() - } - - // ... + .addOnCompleteListener(this) { task -> + Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful) + + // If sign in fails, display a message to the user. If sign in succeeds + // the auth state listener will be notified and logic to handle the + // signed in user can be handled in the listener. + if (!task.isSuccessful) { + Log.w(TAG, "signInWithCredential", task.exception) + Toast.makeText( + baseContext, + "Authentication failed.", + Toast.LENGTH_SHORT, + ).show() } + + // ... + } // [END auth_with_github] } @@ -247,27 +249,26 @@ abstract class MainActivity : AppCompatActivity() { // [START auth_link_and_merge] val prevUser = auth.currentUser auth.signInWithCredential(credential) - .addOnSuccessListener { result -> - val currentUser = result.user - // Merge prevUser and currentUser accounts and data - // ... - } - .addOnFailureListener { - // ... - } + .addOnSuccessListener { result -> + val currentUser = result.user + // Merge prevUser and currentUser accounts and data + // ... + } + .addOnFailureListener { + // ... + } // [END auth_link_and_merge] } private fun unlink(providerId: String) { - // [START auth_unlink] Firebase.auth.currentUser!!.unlink(providerId) - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - // Auth provider unlinked from account - // ... - } + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Auth provider unlinked from account + // ... } + } // [END auth_unlink] } @@ -281,9 +282,10 @@ abstract class MainActivity : AppCompatActivity() { handleCodeInApp = true setIOSBundleId("com.example.ios") setAndroidPackageName( - "com.example.android", - true, /* installIfNotAvailable */ - "12" /* minimumVersion */) + "com.example.android", + true, // installIfNotAvailable + "12", // minimumVersion + ) } // [END auth_build_action_code_settings] } @@ -291,11 +293,11 @@ abstract class MainActivity : AppCompatActivity() { private fun sendSignInLink(email: String, actionCodeSettings: ActionCodeSettings) { // [START auth_send_sign_in_link] Firebase.auth.sendSignInLinkToEmail(email, actionCodeSettings) - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Log.d(TAG, "Email sent.") - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Log.d(TAG, "Email sent.") } + } // [END auth_send_sign_in_link] } @@ -312,80 +314,77 @@ abstract class MainActivity : AppCompatActivity() { // The client SDK will parse the code from the link for you. auth.signInWithEmailLink(email, emailLink) - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Log.d(TAG, "Successfully signed in with email link!") - val result = task.result - // You can access the new user via result.getUser() - // Additional user info profile *not* available via: - // result.getAdditionalUserInfo().getProfile() == null - // You can check if the user is new or existing: - // result.getAdditionalUserInfo().isNewUser() - } else { - Log.e(TAG, "Error signing in with email link", task.exception) - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Log.d(TAG, "Successfully signed in with email link!") + val result = task.result + // You can access the new user via result.getUser() + // Additional user info profile *not* available via: + // result.getAdditionalUserInfo().getProfile() == null + // You can check if the user is new or existing: + // result.getAdditionalUserInfo().isNewUser() + } else { + Log.e(TAG, "Error signing in with email link", task.exception) } + } } // [END auth_verify_sign_in_link] } private fun linkWithSignInLink(email: String, emailLink: String) { - // [START auth_link_with_link] // Construct the email link credential from the current URL. val credential = EmailAuthProvider.getCredentialWithLink(email, emailLink) // Link the credential to the current user. Firebase.auth.currentUser!!.linkWithCredential(credential) - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Log.d(TAG, "Successfully linked emailLink credential!") - val result = task.result - // You can access the new user via result.getUser() - // Additional user info profile *not* available via: - // result.getAdditionalUserInfo().getProfile() == null - // You can check if the user is new or existing: - // result.getAdditionalUserInfo().isNewUser() - } else { - Log.e(TAG, "Error linking emailLink credential", task.exception) - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Log.d(TAG, "Successfully linked emailLink credential!") + val result = task.result + // You can access the new user via result.getUser() + // Additional user info profile *not* available via: + // result.getAdditionalUserInfo().getProfile() == null + // You can check if the user is new or existing: + // result.getAdditionalUserInfo().isNewUser() + } else { + Log.e(TAG, "Error linking emailLink credential", task.exception) } + } // [END auth_link_with_link] } private fun reauthWithLink(email: String, emailLink: String) { - // [START auth_reauth_with_link] // Construct the email link credential from the current URL. val credential = EmailAuthProvider.getCredentialWithLink(email, emailLink) // Re-authenticate the user with this credential. Firebase.auth.currentUser!!.reauthenticateAndRetrieveData(credential) - .addOnCompleteListener { task -> - if (task.isSuccessful) { - // User is now successfully reauthenticated - } else { - Log.e(TAG, "Error reauthenticating", task.exception) - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + // User is now successfully reauthenticated + } else { + Log.e(TAG, "Error reauthenticating", task.exception) } + } // [END auth_reauth_with_link] } private fun differentiateLink(email: String) { - // [START auth_differentiate_link] Firebase.auth.fetchSignInMethodsForEmail(email) - .addOnSuccessListener { result -> - val signInMethods = result.signInMethods!! - if (signInMethods.contains(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD)) { - // User can sign in with email/password - } else if (signInMethods.contains(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD)) { - // User can sign in with email/link - } - } - .addOnFailureListener { exception -> - Log.e(TAG, "Error getting sign in methods for user", exception) + .addOnSuccessListener { result -> + val signInMethods = result.signInMethods!! + if (signInMethods.contains(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD)) { + // User can sign in with email/password + } else if (signInMethods.contains(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD)) { + // User can sign in with email/link } + } + .addOnFailureListener { exception -> + Log.e(TAG, "Error getting sign in methods for user", exception) + } // [END auth_differentiate_link] } @@ -425,32 +424,32 @@ abstract class MainActivity : AppCompatActivity() { // Whenever verification is triggered with the whitelisted number, // provided it is not set for auto-retrieval, onCodeSent will be triggered. val options = PhoneAuthOptions.newBuilder(Firebase.auth) - .setPhoneNumber(phoneNum) - .setTimeout(30L, TimeUnit.SECONDS) - .setActivity(this) - .setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { - - override fun onCodeSent( - verificationId: String, - forceResendingToken: PhoneAuthProvider.ForceResendingToken - ) { - // Save the verification id somewhere - // ... - - // The corresponding whitelisted code above should be used to complete sign-in. - this@MainActivity.enableUserManuallyInputCode() - } + .setPhoneNumber(phoneNum) + .setTimeout(30L, TimeUnit.SECONDS) + .setActivity(this) + .setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { + + override fun onCodeSent( + verificationId: String, + forceResendingToken: PhoneAuthProvider.ForceResendingToken, + ) { + // Save the verification id somewhere + // ... - override fun onVerificationCompleted(phoneAuthCredential: PhoneAuthCredential) { - // Sign in with the credential - // ... - } + // The corresponding whitelisted code above should be used to complete sign-in. + this@MainActivity.enableUserManuallyInputCode() + } - override fun onVerificationFailed(e: FirebaseException) { - // ... - } - }) - .build() + override fun onVerificationCompleted(phoneAuthCredential: PhoneAuthCredential) { + // Sign in with the credential + // ... + } + + override fun onVerificationFailed(e: FirebaseException) { + // ... + } + }) + .build() PhoneAuthProvider.verifyPhoneNumber(options) // [END auth_test_phone_verify] } @@ -472,21 +471,21 @@ abstract class MainActivity : AppCompatActivity() { firebaseAuthSettings.setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber, smsCode) val options = PhoneAuthOptions.newBuilder(firebaseAuth) - .setPhoneNumber(phoneNumber) - .setTimeout(60L, TimeUnit.SECONDS) - .setActivity(this) - .setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { - override fun onVerificationCompleted(credential: PhoneAuthCredential) { - // Instant verification is applied and a credential is directly returned. - // ... - } + .setPhoneNumber(phoneNumber) + .setTimeout(60L, TimeUnit.SECONDS) + .setActivity(this) + .setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { + override fun onVerificationCompleted(credential: PhoneAuthCredential) { + // Instant verification is applied and a credential is directly returned. + // ... + } - // [START_EXCLUDE] - override fun onVerificationFailed(e: FirebaseException) { - } - // [END_EXCLUDE] - }) - .build() + // [START_EXCLUDE] + override fun onVerificationFailed(e: FirebaseException) { + } + // [END_EXCLUDE] + }) + .build() PhoneAuthProvider.verifyPhoneNumber(options) // [END auth_test_phone_auto] } @@ -494,8 +493,8 @@ abstract class MainActivity : AppCompatActivity() { private fun gamesMakeGoogleSignInOptions() { // [START games_google_signin_options] val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN) - .requestServerAuthCode(getString(R.string.default_web_client_id)) - .build() + .requestServerAuthCode(getString(R.string.default_web_client_id)) + .build() // [END games_google_signin_options] } @@ -508,22 +507,25 @@ abstract class MainActivity : AppCompatActivity() { val auth = Firebase.auth val credential = PlayGamesAuthProvider.getCredential(acct.serverAuthCode!!) auth.signInWithCredential(credential) - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - // Sign in success, update UI with the signed-in user's information - Log.d(TAG, "signInWithCredential:success") - val user = auth.currentUser - updateUI(user) - } else { - // If sign in fails, display a message to the user. - Log.w(TAG, "signInWithCredential:failure", task.exception) - Toast.makeText(baseContext, "Authentication failed.", - Toast.LENGTH_SHORT).show() - updateUI(null) - } - - // ... + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Sign in success, update UI with the signed-in user's information + Log.d(TAG, "signInWithCredential:success") + val user = auth.currentUser + updateUI(user) + } else { + // If sign in fails, display a message to the user. + Log.w(TAG, "signInWithCredential:failure", task.exception) + Toast.makeText( + baseContext, + "Authentication failed.", + Toast.LENGTH_SHORT, + ).show() + updateUI(null) } + + // ... + } } // [END games_auth_with_firebase] diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MultiFactorActivity.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MultiFactorActivity.kt index 9e9000d89..4e3860585 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MultiFactorActivity.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MultiFactorActivity.kt @@ -33,17 +33,15 @@ class MultiFactorActivity : Activity() { // [START send_email_verification] val user = auth.currentUser!! user.sendEmailVerification() - .addOnCompleteListener(this) { task -> - // Email verification sent - } + .addOnCompleteListener(this) { task -> + // Email verification sent + } // [END send_email_verification] } private fun reload() { - } private fun updateUI(user: FirebaseUser?) { - } } diff --git a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/PhoneAuthActivity.kt b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/PhoneAuthActivity.kt index 5f9593061..568018d43 100644 --- a/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/PhoneAuthActivity.kt +++ b/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/PhoneAuthActivity.kt @@ -67,7 +67,7 @@ class PhoneAuthActivity : Activity() { override fun onCodeSent( verificationId: String, - token: PhoneAuthProvider.ForceResendingToken + token: PhoneAuthProvider.ForceResendingToken, ) { // The SMS verification code has been sent to the provided phone number, we // now need to ask the user to enter the code and then construct a credential @@ -94,10 +94,10 @@ class PhoneAuthActivity : Activity() { private fun startPhoneNumberVerification(phoneNumber: String) { // [START start_phone_auth] val options = PhoneAuthOptions.newBuilder(auth) - .setPhoneNumber(phoneNumber) // Phone number to verify + .setPhoneNumber(phoneNumber) // Phone number to verify .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit - .setActivity(this) // Activity (for callback binding) - .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks + .setActivity(this) // Activity (for callback binding) + .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks .build() PhoneAuthProvider.verifyPhoneNumber(options) // [END start_phone_auth] @@ -112,14 +112,14 @@ class PhoneAuthActivity : Activity() { // [START resend_verification] private fun resendVerificationCode( phoneNumber: String, - token: PhoneAuthProvider.ForceResendingToken? + token: PhoneAuthProvider.ForceResendingToken?, ) { val optionsBuilder = PhoneAuthOptions.newBuilder(auth) - .setPhoneNumber(phoneNumber) // Phone number to verify + .setPhoneNumber(phoneNumber) // Phone number to verify .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit - .setActivity(this) // (optional) Activity for callback binding + .setActivity(this) // (optional) Activity for callback binding // If no activity is passed, reCAPTCHA verification can not be used. - .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks + .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks if (token != null) { optionsBuilder.setForceResendingToken(token) // callback's ForceResendingToken } @@ -130,26 +130,25 @@ class PhoneAuthActivity : Activity() { // [START sign_in_with_phone] private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) { auth.signInWithCredential(credential) - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - // Sign in success, update UI with the signed-in user's information - Log.d(TAG, "signInWithCredential:success") - - val user = task.result?.user - } else { - // Sign in failed, display a message and update the UI - Log.w(TAG, "signInWithCredential:failure", task.exception) - if (task.exception is FirebaseAuthInvalidCredentialsException) { - // The verification code entered was invalid - } - // Update UI + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Sign in success, update UI with the signed-in user's information + Log.d(TAG, "signInWithCredential:success") + + val user = task.result?.user + } else { + // Sign in failed, display a message and update the UI + Log.w(TAG, "signInWithCredential:failure", task.exception) + if (task.exception is FirebaseAuthInvalidCredentialsException) { + // The verification code entered was invalid } + // Update UI } + } } // [END sign_in_with_phone] private fun updateUI(user: FirebaseUser? = auth.currentUser) { - } companion object { diff --git a/auth/build.gradle b/auth/build.gradle index 302b37ca8..079fc78ec 100644 --- a/auth/build.gradle +++ b/auth/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/build.gradle b/build.gradle index 03418b49b..f169197b7 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } @@ -52,7 +52,7 @@ configurations { } dependencies { - ktlint ("com.pinterest:ktlint:0.48.2") { + ktlint ("com.pinterest:ktlint:0.49.0") { attributes { attribute(Bundling.BUNDLING_ATTRIBUTE, getObjects().named(Bundling, Bundling.EXTERNAL)) } @@ -74,7 +74,7 @@ task("ktlint", type: JavaExec, group: "verification") { mainClass.set("com.pinterest.ktlint.Main") args = [ "--format", - "--android", + "--code-style=android_studio", "--reporter=plain", "--reporter=checkstyle,output=${outputFile}", "**/*.kt", diff --git a/config/app/src/androidTest/java/com/google/firebase/quickstart/config/ExampleInstrumentedTest.kt b/config/app/src/androidTest/java/com/google/firebase/quickstart/config/ExampleInstrumentedTest.kt index 7b3580852..3b9c75f82 100644 --- a/config/app/src/androidTest/java/com/google/firebase/quickstart/config/ExampleInstrumentedTest.kt +++ b/config/app/src/androidTest/java/com/google/firebase/quickstart/config/ExampleInstrumentedTest.kt @@ -1,13 +1,11 @@ package com.google.firebase.quickstart.config -import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 - +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith -import org.junit.Assert.assertEquals - /** * Instrumented test, which will execute on an Android device. * @@ -21,4 +19,4 @@ class ExampleInstrumentedTest { val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.google.firebase.quickstart.config", appContext.packageName) } -} \ No newline at end of file +} diff --git a/config/app/src/main/java/com/google/firebase/quickstart/config/MainActivity.kt b/config/app/src/main/java/com/google/firebase/quickstart/config/MainActivity.kt index 70349154c..e5ff38391 100644 --- a/config/app/src/main/java/com/google/firebase/quickstart/config/MainActivity.kt +++ b/config/app/src/main/java/com/google/firebase/quickstart/config/MainActivity.kt @@ -1,9 +1,9 @@ package com.google.firebase.quickstart.config -import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity import com.google.firebase.ktx.Firebase import com.google.firebase.remoteconfig.ConfigUpdate import com.google.firebase.remoteconfig.ConfigUpdateListener @@ -40,11 +40,17 @@ class MainActivity : AppCompatActivity() { if (task.isSuccessful) { val updated = task.result Log.d(TAG, "Config params updated: $updated") - Toast.makeText(this, "Fetch and activate succeeded", - Toast.LENGTH_SHORT).show() + Toast.makeText( + this, + "Fetch and activate succeeded", + Toast.LENGTH_SHORT, + ).show() } else { - Toast.makeText(this, "Fetch failed", - Toast.LENGTH_SHORT).show() + Toast.makeText( + this, + "Fetch failed", + Toast.LENGTH_SHORT, + ).show() } displayWelcomeMessage() } @@ -52,8 +58,8 @@ class MainActivity : AppCompatActivity() { // [START add_config_update_listener] remoteConfig.addOnConfigUpdateListener(object : ConfigUpdateListener { - override fun onUpdate(configUpdate : ConfigUpdate) { - Log.d(TAG, "Updated keys: " + configUpdate.updatedKeys); + override fun onUpdate(configUpdate: ConfigUpdate) { + Log.d(TAG, "Updated keys: " + configUpdate.updatedKeys) if (configUpdate.updatedKeys.contains("welcome_message")) { remoteConfig.activate().addOnCompleteListener { @@ -83,4 +89,4 @@ class MainActivity : AppCompatActivity() { // Remote Config keys private const val WELCOME_MESSAGE_KEY = "welcome_message" } -} \ No newline at end of file +} diff --git a/config/app/src/test/java/com/google/firebase/quickstart/config/ExampleUnitTest.kt b/config/app/src/test/java/com/google/firebase/quickstart/config/ExampleUnitTest.kt index 47d481887..2c43cd4ab 100644 --- a/config/app/src/test/java/com/google/firebase/quickstart/config/ExampleUnitTest.kt +++ b/config/app/src/test/java/com/google/firebase/quickstart/config/ExampleUnitTest.kt @@ -1,8 +1,7 @@ package com.google.firebase.quickstart.config -import org.junit.Test - import org.junit.Assert.assertEquals +import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). @@ -14,4 +13,4 @@ class ExampleUnitTest { fun addition_isCorrect() { assertEquals(4, 2 + 2) } -} \ No newline at end of file +} diff --git a/config/build.gradle b/config/build.gradle index 302b37ca8..079fc78ec 100644 --- a/config/build.gradle +++ b/config/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/crashlytics/app/src/main/java/com/google/firebase/example/crashlytics/kotlin/MainActivity.kt b/crashlytics/app/src/main/java/com/google/firebase/example/crashlytics/kotlin/MainActivity.kt index 4413d3aa7..712c25e0c 100644 --- a/crashlytics/app/src/main/java/com/google/firebase/example/crashlytics/kotlin/MainActivity.kt +++ b/crashlytics/app/src/main/java/com/google/firebase/example/crashlytics/kotlin/MainActivity.kt @@ -19,10 +19,10 @@ class MainActivity : AppCompatActivity() { val crashlytics = Firebase.crashlytics crashlytics.setCustomKeys { key("my_string_key", "foo") // String value - key("my_bool_key", true) // boolean value - key("my_double_key", 1.0) // double value - key("my_float_key", 1.0f) // float value - key("my_int_key", 1) // int value + key("my_bool_key", true) // boolean value + key("my_double_key", 1.0) // double value + key("my_float_key", 1.0f) // float value + key("my_int_key", 1) // int value } // [END crash_set_keys_basic] } @@ -85,9 +85,13 @@ class MainActivity : AppCompatActivity() { throw RuntimeException() // Force a crash } - addContentView(crashButton, ViewGroup.LayoutParams( + addContentView( + crashButton, + ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT)) + ViewGroup.LayoutParams.WRAP_CONTENT, + ), + ) // [END crash_force_crash] } } diff --git a/crashlytics/build.gradle b/crashlytics/build.gradle index c53575bc5..74abecaa0 100644 --- a/crashlytics/build.gradle +++ b/crashlytics/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" classpath 'com.google.firebase:firebase-crashlytics-gradle:2.9.5' } } diff --git a/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/QueryActivity.kt b/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/QueryActivity.kt index 4b92f5219..7b86801b3 100644 --- a/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/QueryActivity.kt +++ b/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/QueryActivity.kt @@ -136,7 +136,7 @@ abstract class QueryActivity : AppCompatActivity() { // [START rtdb_order_by_nested] // Most viewed posts val myMostViewedPostsQuery = databaseReference.child("posts") - .orderByChild("metrics/views") + .orderByChild("metrics/views") myMostViewedPostsQuery.addChildEventListener(object : ChildEventListener { // TODO: implement the ChildEventListener methods as documented above // [START_EXCLUDE] @@ -201,8 +201,11 @@ abstract class QueryActivity : AppCompatActivity() { override fun onCancelled(databaseError: DatabaseError) { Log.w(TAG, "postComments:onCancelled", databaseError.toException()) - Toast.makeText(context, "Failed to load comments.", - Toast.LENGTH_SHORT).show() + Toast.makeText( + context, + "Failed to load comments.", + Toast.LENGTH_SHORT, + ).show() } } databaseReference.addChildEventListener(childEventListener) diff --git a/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/ReadAndWriteSnippets.kt b/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/ReadAndWriteSnippets.kt index 74efe82d9..7f010e504 100644 --- a/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/ReadAndWriteSnippets.kt +++ b/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/ReadAndWriteSnippets.kt @@ -1,19 +1,18 @@ package com.google.firebase.referencecode.database.kotlin import android.util.Log +import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference -import com.google.firebase.database.DataSnapshot import com.google.firebase.database.MutableData +import com.google.firebase.database.ServerValue import com.google.firebase.database.Transaction import com.google.firebase.database.ValueEventListener -import com.google.firebase.database.ServerValue import com.google.firebase.database.ktx.database import com.google.firebase.database.ktx.getValue import com.google.firebase.ktx.Firebase import com.google.firebase.referencecode.database.kotlin.models.Post import com.google.firebase.referencecode.database.models.User -import java.util.HashMap abstract class ReadAndWriteSnippets { @@ -42,14 +41,14 @@ abstract class ReadAndWriteSnippets { // [START rtdb_write_new_user_task] database.child("users").child(userId).setValue(user) - .addOnSuccessListener { - // Write was successful! - // ... - } - .addOnFailureListener { - // Write failed - // ... - } + .addOnSuccessListener { + // Write was successful! + // ... + } + .addOnFailureListener { + // Write failed + // ... + } // [END rtdb_write_new_user_task] } @@ -85,15 +84,14 @@ abstract class ReadAndWriteSnippets { val postValues = post.toMap() val childUpdates = hashMapOf( - "/posts/$key" to postValues, - "/user-posts/$userId/$key" to postValues + "/posts/$key" to postValues, + "/user-posts/$userId/$key" to postValues, ) database.updateChildren(childUpdates) } // [END write_fan_out] - // [START post_stars_transaction] private fun onStarClicked(postRef: DatabaseReference) { // [START_EXCLUDE] @@ -102,7 +100,7 @@ abstract class ReadAndWriteSnippets { postRef.runTransaction(object : Transaction.Handler { override fun doTransaction(mutableData: MutableData): Transaction.Result { val p = mutableData.getValue(Post::class.java) - ?: return Transaction.success(mutableData) + ?: return Transaction.success(mutableData) if (p.stars.containsKey(uid)) { // Unstar the post and remove self from stars @@ -120,9 +118,9 @@ abstract class ReadAndWriteSnippets { } override fun onComplete( - databaseError: DatabaseError?, - committed: Boolean, - currentData: DataSnapshot? + databaseError: DatabaseError?, + committed: Boolean, + currentData: DataSnapshot?, ) { // Transaction completed Log.d(TAG, "postTransaction:onComplete:" + databaseError!!) @@ -137,7 +135,7 @@ abstract class ReadAndWriteSnippets { "posts/$key/stars/$uid" to true, "posts/$key/starCount" to ServerValue.increment(1), "user-posts/$uid/$key/stars/$uid" to true, - "user-posts/$uid/$key/starCount" to ServerValue.increment(1) + "user-posts/$uid/$key/starCount" to ServerValue.increment(1), ) database.updateChildren(updates) } diff --git a/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/models/Comment.kt b/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/models/Comment.kt index 72ecd1b25..9d5e56714 100644 --- a/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/models/Comment.kt +++ b/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/models/Comment.kt @@ -7,6 +7,6 @@ import com.google.firebase.database.IgnoreExtraProperties data class Comment( var uid: String? = "", var author: String? = "", - var text: String? = "" + var text: String? = "", ) -// [END comment_class] \ No newline at end of file +// [END comment_class] diff --git a/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/models/Post.kt b/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/models/Post.kt index 4a8329e32..c4eb1575c 100644 --- a/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/models/Post.kt +++ b/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/models/Post.kt @@ -12,21 +12,21 @@ data class Post( var title: String? = "", var body: String? = "", var starCount: Int = 0, - var stars: MutableMap = HashMap() + var stars: MutableMap = HashMap(), ) { // [START post_to_map] @Exclude fun toMap(): Map { return mapOf( - "uid" to uid, - "author" to author, - "title" to title, - "body" to body, - "starCount" to starCount, - "stars" to stars + "uid" to uid, + "author" to author, + "title" to title, + "body" to body, + "starCount" to starCount, + "stars" to stars, ) } // [END post_to_map] } -// [END post_class] \ No newline at end of file +// [END post_class] diff --git a/database/build.gradle b/database/build.gradle index f6aeb0b0b..493e4e71a 100644 --- a/database/build.gradle +++ b/database/build.gradle @@ -9,7 +9,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/model/InviteContent.kt b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/model/InviteContent.kt index 9813b7756..73a5d9f69 100644 --- a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/model/InviteContent.kt +++ b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/model/InviteContent.kt @@ -13,6 +13,6 @@ data class InviteContent( /** The body of the message. Indispensable content should go here. */ val body: String?, /** The URL containing the link to invite. In link-copy cases, only this field will be used. */ - val link: Uri + val link: Uri, ) // [END ddl_invite_content] diff --git a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/CopyPresenter.kt b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/CopyPresenter.kt index 1423e906d..9012c0649 100644 --- a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/CopyPresenter.kt +++ b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/CopyPresenter.kt @@ -2,7 +2,6 @@ package com.google.firebase.dynamicinvites.kotlin.presenter import android.content.Context import android.widget.Toast - import com.google.firebase.dynamicinvites.R import com.google.firebase.dynamicinvites.kotlin.model.InviteContent diff --git a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/EmailPresenter.kt b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/EmailPresenter.kt index f641d819a..2f3f40557 100644 --- a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/EmailPresenter.kt +++ b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/EmailPresenter.kt @@ -2,7 +2,6 @@ package com.google.firebase.dynamicinvites.kotlin.presenter import android.content.Context import android.widget.Toast - import com.google.firebase.dynamicinvites.R import com.google.firebase.dynamicinvites.kotlin.model.InviteContent diff --git a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/InvitePresenter.kt b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/InvitePresenter.kt index 26fd79100..08bd7d6f3 100644 --- a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/InvitePresenter.kt +++ b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/InvitePresenter.kt @@ -2,7 +2,6 @@ package com.google.firebase.dynamicinvites.kotlin.presenter import android.content.Context import androidx.annotation.DrawableRes - import com.google.firebase.dynamicinvites.kotlin.model.InviteContent // [START ddl_invite_presenter] @@ -18,7 +17,7 @@ open class InvitePresenter( /** Whether or not the method is available on this device. For example, SMS is phone only. */ val isAvailable: Boolean, /** The Content of the invitation */ - val content: InviteContent + val content: InviteContent, ) { /** * Send the invitation using the specified method. diff --git a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/MessagePresenter.kt b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/MessagePresenter.kt index 3026fdd62..5f4745204 100644 --- a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/MessagePresenter.kt +++ b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/MessagePresenter.kt @@ -2,7 +2,6 @@ package com.google.firebase.dynamicinvites.kotlin.presenter import android.content.Context import android.widget.Toast - import com.google.firebase.dynamicinvites.R import com.google.firebase.dynamicinvites.kotlin.model.InviteContent diff --git a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/SocialPresenter.kt b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/SocialPresenter.kt index b3b55e4f6..cd448cce4 100644 --- a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/SocialPresenter.kt +++ b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/SocialPresenter.kt @@ -2,7 +2,6 @@ package com.google.firebase.dynamicinvites.kotlin.presenter import android.content.Context import android.widget.Toast - import com.google.firebase.dynamicinvites.R import com.google.firebase.dynamicinvites.kotlin.model.InviteContent diff --git a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/util/DynamicLinksUtil.kt b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/util/DynamicLinksUtil.kt index 62a2e283e..8b9c8334a 100644 --- a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/util/DynamicLinksUtil.kt +++ b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/util/DynamicLinksUtil.kt @@ -1,7 +1,6 @@ package com.google.firebase.dynamicinvites.kotlin.util import android.net.Uri - import com.google.firebase.dynamicinvites.kotlin.model.InviteContent import com.google.firebase.dynamiclinks.DynamicLink import com.google.firebase.dynamiclinks.FirebaseDynamicLinks @@ -10,9 +9,10 @@ object DynamicLinksUtil { fun generateInviteContent(): InviteContent { return InviteContent( - "Hey check out my great app!", - "It's like the best app ever.", - generateContentLink()) + "Hey check out my great app!", + "It's like the best app ever.", + generateContentLink(), + ) } // [START ddl_generate_content_link] @@ -21,12 +21,12 @@ object DynamicLinksUtil { val domain = "https://your-app.page.link" val link = FirebaseDynamicLinks.getInstance() - .createDynamicLink() - .setLink(baseUrl) - .setDomainUriPrefix(domain) - .setIosParameters(DynamicLink.IosParameters.Builder("com.your.bundleid").build()) - .setAndroidParameters(DynamicLink.AndroidParameters.Builder("com.your.packageName").build()) - .buildDynamicLink() + .createDynamicLink() + .setLink(baseUrl) + .setDomainUriPrefix(domain) + .setIosParameters(DynamicLink.IosParameters.Builder("com.your.bundleid").build()) + .setAndroidParameters(DynamicLink.AndroidParameters.Builder("com.your.packageName").build()) + .buildDynamicLink() return link.uri } diff --git a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/view/AdvancedActivity.kt b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/view/AdvancedActivity.kt index 18bbb0370..b7f0cb7d9 100644 --- a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/view/AdvancedActivity.kt +++ b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/view/AdvancedActivity.kt @@ -3,7 +3,6 @@ package com.google.firebase.dynamicinvites.kotlin.view import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity - import com.google.firebase.dynamicinvites.R import com.google.firebase.dynamicinvites.kotlin.presenter.InvitePresenter diff --git a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/view/ShareDialogFragment.kt b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/view/ShareDialogFragment.kt index 8969b3a26..a8551b73d 100644 --- a/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/view/ShareDialogFragment.kt +++ b/dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/view/ShareDialogFragment.kt @@ -39,7 +39,7 @@ class ShareDialogFragment : BottomSheetDialogFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? + savedInstanceState: Bundle?, ): View? { return inflater.inflate(R.layout.fragment_item_list_dialog, container, false) } @@ -47,11 +47,11 @@ class ShareDialogFragment : BottomSheetDialogFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val content = DynamicLinksUtil.generateInviteContent() val presenters = listOf( - EmailPresenter(true, content), - SocialPresenter(true, content), - MessagePresenter(true, content), - CopyPresenter(true, content), - MorePresenter(true, content) + EmailPresenter(true, content), + SocialPresenter(true, content), + MessagePresenter(true, content), + CopyPresenter(true, content), + MorePresenter(true, content), ) val recycler = view.findViewById(R.id.recycler) diff --git a/dl-invites/build.gradle b/dl-invites/build.gradle index 0145c30c5..87591c53d 100644 --- a/dl-invites/build.gradle +++ b/dl-invites/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/dynamic-links/app/src/main/java/com/google/firebase/quickstart/dynamiclinks/kotlin/MainActivity.kt b/dynamic-links/app/src/main/java/com/google/firebase/quickstart/dynamiclinks/kotlin/MainActivity.kt index ec6f00016..94842a3f4 100644 --- a/dynamic-links/app/src/main/java/com/google/firebase/quickstart/dynamiclinks/kotlin/MainActivity.kt +++ b/dynamic-links/app/src/main/java/com/google/firebase/quickstart/dynamiclinks/kotlin/MainActivity.kt @@ -46,7 +46,6 @@ abstract class MainActivity : AppCompatActivity() { // content, or apply promotional credit to the user's // account. // ... - } .addOnFailureListener(this) { e -> Log.w(TAG, "getDynamicLink:onFailure", e) } // [END get_deep_link] @@ -98,7 +97,6 @@ abstract class MainActivity : AppCompatActivity() { } private fun processShortLink(shortLink: Uri?, previewLink: Uri?) { - } fun createShortLink() { @@ -124,8 +122,10 @@ abstract class MainActivity : AppCompatActivity() { fun shortenLongLink() { // [START shorten_long_link] val shortLinkTask = Firebase.dynamicLinks.shortLinkAsync { - longLink = Uri.parse("https://example.page.link/?link=" + - "https://www.example.com/&apn=com.example.android&ibn=com.example.ios") + longLink = Uri.parse( + "https://example.page.link/?link=" + + "https://www.example.com/&apn=com.example.android&ibn=com.example.ios", + ) }.addOnSuccessListener { (shortLink, flowChartLink) -> // You'll need to import com.google.firebase.dynamiclinks.ktx.component1 and // com.google.firebase.dynamiclinks.ktx.component2 @@ -163,19 +163,19 @@ abstract class MainActivity : AppCompatActivity() { fun getInvitation() { // [START ddl_get_invitation] Firebase.dynamicLinks - .getDynamicLink(intent) - .addOnCompleteListener { task -> - if (!task.isSuccessful) { - // Handle error - // ... - } - - val invite = FirebaseAppInvite.getInvitation(task.result) - if (invite != null) { - // Handle invite - // ... - } + .getDynamicLink(intent) + .addOnCompleteListener { task -> + if (!task.isSuccessful) { + // Handle error + // ... } + + val invite = FirebaseAppInvite.getInvitation(task.result) + if (invite != null) { + // Handle invite + // ... + } + } // [END ddl_get_invitation] } diff --git a/dynamic-links/app/src/main/java/com/google/firebase/quickstart/dynamiclinks/kotlin/ReferralActivity.kt b/dynamic-links/app/src/main/java/com/google/firebase/quickstart/dynamiclinks/kotlin/ReferralActivity.kt index 58d3299a5..3f1ff8d21 100644 --- a/dynamic-links/app/src/main/java/com/google/firebase/quickstart/dynamiclinks/kotlin/ReferralActivity.kt +++ b/dynamic-links/app/src/main/java/com/google/firebase/quickstart/dynamiclinks/kotlin/ReferralActivity.kt @@ -50,8 +50,11 @@ abstract class ReferralActivity : AppCompatActivity() { val subject = String.format("%s wants you to play MyExampleGame!", referrerName) val invitationLink = mInvitationUrl.toString() val msg = "Let's play MyExampleGame together! Use my referrer link: $invitationLink" - val msgHtml = String.format("

Let's play MyExampleGame together! Use my " + - "referrer link!

", invitationLink) + val msgHtml = String.format( + "

Let's play MyExampleGame together! Use my " + + "referrer link!

", + invitationLink, + ) val intent = Intent(Intent.ACTION_SENDTO).apply { data = Uri.parse("mailto:") // only email apps should handle this @@ -72,40 +75,41 @@ abstract class ReferralActivity : AppCompatActivity() { // ... Firebase.dynamicLinks - .getDynamicLink(intent) - .addOnSuccessListener(this) { pendingDynamicLinkData -> - // Get deep link from result (may be null if no link is found) - var deepLink: Uri? = null - if (pendingDynamicLinkData != null) { - deepLink = pendingDynamicLinkData.link - } - // - // If the user isn't signed in and the pending Dynamic Link is - // an invitation, sign in the user anonymously, and record the - // referrer's UID. - // - val user = Firebase.auth.currentUser - if (user == null && - deepLink != null && - deepLink.getBooleanQueryParameter("invitedby", false)) { - val referrerUid = deepLink.getQueryParameter("invitedby") - createAnonymousAccountWithReferrerInfo(referrerUid) - } + .getDynamicLink(intent) + .addOnSuccessListener(this) { pendingDynamicLinkData -> + // Get deep link from result (may be null if no link is found) + var deepLink: Uri? = null + if (pendingDynamicLinkData != null) { + deepLink = pendingDynamicLinkData.link } + // + // If the user isn't signed in and the pending Dynamic Link is + // an invitation, sign in the user anonymously, and record the + // referrer's UID. + // + val user = Firebase.auth.currentUser + if (user == null && + deepLink != null && + deepLink.getBooleanQueryParameter("invitedby", false) + ) { + val referrerUid = deepLink.getQueryParameter("invitedby") + createAnonymousAccountWithReferrerInfo(referrerUid) + } + } } private fun createAnonymousAccountWithReferrerInfo(referrerUid: String?) { Firebase.auth - .signInAnonymously() - .addOnSuccessListener { - // Keep track of the referrer in the RTDB. Database calls - // will depend on the structure of your app's RTDB. - val user = Firebase.auth.currentUser - val userRecord = Firebase.database.reference - .child("users") - .child(user!!.uid) - userRecord.child("referred_by").setValue(referrerUid) - } + .signInAnonymously() + .addOnSuccessListener { + // Keep track of the referrer in the RTDB. Database calls + // will depend on the structure of your app's RTDB. + val user = Firebase.auth.currentUser + val userRecord = Firebase.database.reference + .child("users") + .child(user!!.uid) + userRecord.child("referred_by").setValue(referrerUid) + } } // [END ddl_referral_on_create] @@ -118,30 +122,30 @@ abstract class ReferralActivity : AppCompatActivity() { fun linkCredential(credential: AuthCredential) { // [START ddl_referral_link_cred] Firebase.auth.currentUser!! - .linkWithCredential(credential) - .addOnSuccessListener { - // Complete any post sign-up tasks here. - } + .linkWithCredential(credential) + .addOnSuccessListener { + // Complete any post sign-up tasks here. + } // [END ddl_referral_link_cred] } fun rewardUser(credential: AuthCredential) { // [START ddl_referral_reward_user] Firebase.auth.currentUser!! - .linkWithCredential(credential) - .addOnSuccessListener { - // Complete any post sign-up tasks here. + .linkWithCredential(credential) + .addOnSuccessListener { + // Complete any post sign-up tasks here. - // Trigger the sign-up reward function by creating the - // "last_signin_at" field. (If this is a value you want to track, - // you would also update this field in the success listeners of - // your Firebase Authentication signIn calls.) - val user = Firebase.auth.currentUser!! - val userRecord = Firebase.database.reference - .child("users") - .child(user.uid) - userRecord.child("last_signin_at").setValue(ServerValue.TIMESTAMP) - } + // Trigger the sign-up reward function by creating the + // "last_signin_at" field. (If this is a value you want to track, + // you would also update this field in the success listeners of + // your Firebase Authentication signIn calls.) + val user = Firebase.auth.currentUser!! + val userRecord = Firebase.database.reference + .child("users") + .child(user.uid) + userRecord.child("last_signin_at").setValue(ServerValue.TIMESTAMP) + } // [END ddl_referral_reward_user] } } diff --git a/dynamic-links/build.gradle b/dynamic-links/build.gradle index 302b37ca8..079fc78ec 100644 --- a/dynamic-links/build.gradle +++ b/dynamic-links/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/firebaseoptions/app/src/main/java/devrel/firebase/google/com/firebaseoptions/kotlin/MainActivity.kt b/firebaseoptions/app/src/main/java/devrel/firebase/google/com/firebaseoptions/kotlin/MainActivity.kt index cb8306068..2ecf4f14d 100644 --- a/firebaseoptions/app/src/main/java/devrel/firebase/google/com/firebaseoptions/kotlin/MainActivity.kt +++ b/firebaseoptions/app/src/main/java/devrel/firebase/google/com/firebaseoptions/kotlin/MainActivity.kt @@ -21,17 +21,17 @@ class MainActivity : AppCompatActivity() { // - App ID // - API Key val options = FirebaseOptions.Builder() - .setProjectId("my-firebase-project") - .setApplicationId("1:27992087142:android:ce3b6448250083d1") - .setApiKey("AIzaSyADUe90ULnQDuGShD9W23RDP0xmeDc6Mvw") - // .setDatabaseUrl(...) - // .setStorageBucket(...) - .build() + .setProjectId("my-firebase-project") + .setApplicationId("1:27992087142:android:ce3b6448250083d1") + .setApiKey("AIzaSyADUe90ULnQDuGShD9W23RDP0xmeDc6Mvw") + // .setDatabaseUrl(...) + // .setStorageBucket(...) + .build() // [END firebase_options] // [START firebase_secondary] // Initialize secondary FirebaseApp. - Firebase.initialize(this /* Context */, options, "secondary") + Firebase.initialize(context = this, options, "secondary") // Retrieve secondary FirebaseApp. val secondary = Firebase.app("secondary") diff --git a/firebaseoptions/build.gradle b/firebaseoptions/build.gradle index 302b37ca8..079fc78ec 100644 --- a/firebaseoptions/build.gradle +++ b/firebaseoptions/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/firestore/app/src/main/java/com/google/example/firestore/kotlin/DocSnippets.kt b/firestore/app/src/main/java/com/google/example/firestore/kotlin/DocSnippets.kt index 1be9d8322..ff07b4081 100644 --- a/firestore/app/src/main/java/com/google/example/firestore/kotlin/DocSnippets.kt +++ b/firestore/app/src/main/java/com/google/example/firestore/kotlin/DocSnippets.kt @@ -3,15 +3,9 @@ package com.google.example.firestore.kotlin import android.util.Log -import androidx.annotation.WorkerThread -import com.google.android.gms.tasks.Task -import com.google.android.gms.tasks.Tasks import com.google.firebase.Timestamp import com.google.firebase.firestore.AggregateSource -import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.DocumentChange -import com.google.firebase.firestore.DocumentSnapshot -import com.google.firebase.firestore.FieldPath import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException @@ -28,8 +22,6 @@ import com.google.firebase.ktx.Firebase import java.util.ArrayList import java.util.Date import java.util.HashMap -import java.util.concurrent.Callable -import java.util.concurrent.Executor import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit @@ -44,8 +36,12 @@ abstract class DocSnippets(val db: FirebaseFirestore) { private val TAG = "DocSnippets" - private val EXECUTOR = ThreadPoolExecutor(2, 4, - 60, TimeUnit.SECONDS, LinkedBlockingQueue() + private val EXECUTOR = ThreadPoolExecutor( + 2, + 4, + 60, + TimeUnit.SECONDS, + LinkedBlockingQueue(), ) } @@ -131,9 +127,9 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // [START add_ada_lovelace] // Create a new user with a first and last name val user = hashMapOf( - "first" to "Ada", - "last" to "Lovelace", - "born" to 1815 + "first" to "Ada", + "last" to "Lovelace", + "born" to 1815, ) // Add a new document with a generated ID @@ -152,10 +148,10 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // [START add_alan_turing] // Create a new user with a first, middle, and last name val user = hashMapOf( - "first" to "Alan", - "middle" to "Mathison", - "last" to "Turing", - "born" to 1912 + "first" to "Alan", + "middle" to "Mathison", + "last" to "Turing", + "born" to 1912, ) // Add a new document with a generated ID @@ -173,15 +169,15 @@ abstract class DocSnippets(val db: FirebaseFirestore) { private fun getAllUsers() { // [START get_all_users] db.collection("users") - .get() - .addOnSuccessListener { result -> - for (document in result) { - Log.d(TAG, "${document.id} => ${document.data}") - } - } - .addOnFailureListener { exception -> - Log.w(TAG, "Error getting documents.", exception) + .get() + .addOnSuccessListener { result -> + for (document in result) { + Log.d(TAG, "${document.id} => ${document.data}") } + } + .addOnFailureListener { exception -> + Log.w(TAG, "Error getting documents.", exception) + } // [END get_all_users] } @@ -192,15 +188,15 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // You will get a first snapshot with the initial results and a new // snapshot each time there is a change in the results. db.collection("users") - .whereLessThan("born", 1900) - .addSnapshotListener { snapshots, e -> - if (e != null) { - Log.w(TAG, "Listen failed.", e) - return@addSnapshotListener - } - - Log.d(TAG, "Current users born before 1900: $snapshots") + .whereLessThan("born", 1900) + .addSnapshotListener { snapshots, e -> + if (e != null) { + Log.w(TAG, "Listen failed.", e) + return@addSnapshotListener } + + Log.d(TAG, "Current users born before 1900: $snapshots") + } // [END listen_for_users] } @@ -219,8 +215,8 @@ abstract class DocSnippets(val db: FirebaseFirestore) { private fun subcollectionReference() { // [START subcollection_reference] val messageRef = db - .collection("rooms").document("roomA") - .collection("messages").document("message1") + .collection("rooms").document("roomA") + .collection("messages").document("message1") // [END subcollection_reference] } @@ -238,22 +234,22 @@ abstract class DocSnippets(val db: FirebaseFirestore) { @field:JvmField // use this annotation if your Boolean field is prefixed with 'is' val isCapital: Boolean? = null, val population: Long? = null, - val regions: List? = null + val regions: List? = null, ) // [END city_class] private fun setDocument() { // [START set_document] val city = hashMapOf( - "name" to "Los Angeles", - "state" to "CA", - "country" to "USA" + "name" to "Los Angeles", + "state" to "CA", + "country" to "USA", ) db.collection("cities").document("LA") - .set(city) - .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") } - .addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) } + .set(city) + .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") } + .addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) } // [END set_document] val data = HashMap() @@ -266,32 +262,38 @@ abstract class DocSnippets(val db: FirebaseFirestore) { private fun dataTypes() { // [START data_types] val docData = hashMapOf( - "stringExample" to "Hello world!", - "booleanExample" to true, - "numberExample" to 3.14159265, - "dateExample" to Timestamp(Date()), - "listExample" to arrayListOf(1, 2, 3), - "nullExample" to null + "stringExample" to "Hello world!", + "booleanExample" to true, + "numberExample" to 3.14159265, + "dateExample" to Timestamp(Date()), + "listExample" to arrayListOf(1, 2, 3), + "nullExample" to null, ) val nestedData = hashMapOf( - "a" to 5, - "b" to true + "a" to 5, + "b" to true, ) docData["objectExample"] = nestedData db.collection("data").document("one") - .set(docData) - .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") } - .addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) } + .set(docData) + .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") } + .addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) } // [END data_types] } fun addCustomClass() { // [START add_custom_class] - val city = City("Los Angeles", "CA", "USA", - false, 5000000L, listOf("west_coast", "socal")) + val city = City( + "Los Angeles", + "CA", + "USA", + false, + 5000000L, + listOf("west_coast", "socal"), + ) db.collection("cities").document("LA").set(city) // [END add_custom_class] } @@ -300,8 +302,8 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // [START add_document] // Add a new document with a generated id. val data = hashMapOf( - "name" to "Tokyo", - "country" to "Japan" + "name" to "Tokyo", + "country" to "Japan", ) db.collection("cities") @@ -332,9 +334,9 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // Set the "isCapital" field of the city 'DC' washingtonRef - .update("capital", true) - .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated!") } - .addOnFailureListener { e -> Log.w(TAG, "Error updating document", e) } + .update("capital", true) + .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated!") } + .addOnFailureListener { e -> Log.w(TAG, "Error updating document", e) } // [END update_document] } @@ -370,10 +372,12 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // // To update age and favorite color: db.collection("users").document("frank") - .update(mapOf( - "age" to 13, - "favorites.color" to "Red" - )) + .update( + mapOf( + "age" to 13, + "favorites.color" to "Red", + ), + ) // [END update_document_nested] } @@ -383,16 +387,16 @@ abstract class DocSnippets(val db: FirebaseFirestore) { val data = hashMapOf("capital" to true) db.collection("cities").document("BJ") - .set(data, SetOptions.merge()) + .set(data, SetOptions.merge()) // [END set_field_with_merge] } private fun deleteDocument() { // [START delete_document] db.collection("cities").document("DC") - .delete() - .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") } - .addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) } + .delete() + .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") } + .addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) } // [END delete_document] } @@ -411,7 +415,7 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // Success null }.addOnSuccessListener { Log.d(TAG, "Transaction success!") } - .addOnFailureListener { e -> Log.w(TAG, "Transaction failure.", e) } + .addOnFailureListener { e -> Log.w(TAG, "Transaction failure.", e) } // [END transactions] } @@ -426,8 +430,10 @@ abstract class DocSnippets(val db: FirebaseFirestore) { transaction.update(sfDocRef, "population", newPopulation) newPopulation } else { - throw FirebaseFirestoreException("Population too high", - FirebaseFirestoreException.Code.ABORTED) + throw FirebaseFirestoreException( + "Population too high", + FirebaseFirestoreException.Code.ABORTED, + ) } }.addOnSuccessListener { result -> Log.d(TAG, "Transaction success: $result") @@ -463,16 +469,16 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // [START get_document] val docRef = db.collection("cities").document("SF") docRef.get() - .addOnSuccessListener { document -> - if (document != null) { - Log.d(TAG, "DocumentSnapshot data: ${document.data}") - } else { - Log.d(TAG, "No such document") - } - } - .addOnFailureListener { exception -> - Log.d(TAG, "get failed with ", exception) + .addOnSuccessListener { document -> + if (document != null) { + Log.d(TAG, "DocumentSnapshot data: ${document.data}") + } else { + Log.d(TAG, "No such document") } + } + .addOnFailureListener { exception -> + Log.d(TAG, "get failed with ", exception) + } // [END get_document] } @@ -532,10 +538,11 @@ abstract class DocSnippets(val db: FirebaseFirestore) { return@addSnapshotListener } - val source = if (snapshot != null && snapshot.metadata.hasPendingWrites()) + val source = if (snapshot != null && snapshot.metadata.hasPendingWrites()) { "Local" - else + } else { "Server" + } if (snapshot != null && snapshot.exists()) { Log.d(TAG, "$source data: ${snapshot.data}") @@ -559,96 +566,96 @@ abstract class DocSnippets(val db: FirebaseFirestore) { private fun getMultipleDocs() { // [START get_multiple] db.collection("cities") - .whereEqualTo("capital", true) - .get() - .addOnSuccessListener { documents -> - for (document in documents) { - Log.d(TAG, "${document.id} => ${document.data}") - } - } - .addOnFailureListener { exception -> - Log.w(TAG, "Error getting documents: ", exception) + .whereEqualTo("capital", true) + .get() + .addOnSuccessListener { documents -> + for (document in documents) { + Log.d(TAG, "${document.id} => ${document.data}") } + } + .addOnFailureListener { exception -> + Log.w(TAG, "Error getting documents: ", exception) + } // [END get_multiple] } private fun getAllDocs() { // [START get_multiple_all] db.collection("cities") - .get() - .addOnSuccessListener { result -> - for (document in result) { - Log.d(TAG, "${document.id} => ${document.data}") - } - } - .addOnFailureListener { exception -> - Log.d(TAG, "Error getting documents: ", exception) + .get() + .addOnSuccessListener { result -> + for (document in result) { + Log.d(TAG, "${document.id} => ${document.data}") } + } + .addOnFailureListener { exception -> + Log.d(TAG, "Error getting documents: ", exception) + } // [END get_multiple_all] } private fun listenToMultiple() { // [START listen_multiple] db.collection("cities") - .whereEqualTo("state", "CA") - .addSnapshotListener { value, e -> - if (e != null) { - Log.w(TAG, "Listen failed.", e) - return@addSnapshotListener - } + .whereEqualTo("state", "CA") + .addSnapshotListener { value, e -> + if (e != null) { + Log.w(TAG, "Listen failed.", e) + return@addSnapshotListener + } - val cities = ArrayList() - for (doc in value!!) { - doc.getString("name")?.let { - cities.add(it) - } + val cities = ArrayList() + for (doc in value!!) { + doc.getString("name")?.let { + cities.add(it) } - Log.d(TAG, "Current cites in CA: $cities") } + Log.d(TAG, "Current cites in CA: $cities") + } // [END listen_multiple] } private fun listenToDiffs() { // [START listen_diffs] db.collection("cities") - .whereEqualTo("state", "CA") - .addSnapshotListener { snapshots, e -> - if (e != null) { - Log.w(TAG, "listen:error", e) - return@addSnapshotListener - } + .whereEqualTo("state", "CA") + .addSnapshotListener { snapshots, e -> + if (e != null) { + Log.w(TAG, "listen:error", e) + return@addSnapshotListener + } - for (dc in snapshots!!.documentChanges) { - when (dc.type) { - DocumentChange.Type.ADDED -> Log.d(TAG, "New city: ${dc.document.data}") - DocumentChange.Type.MODIFIED -> Log.d(TAG, "Modified city: ${dc.document.data}") - DocumentChange.Type.REMOVED -> Log.d(TAG, "Removed city: ${dc.document.data}") - } + for (dc in snapshots!!.documentChanges) { + when (dc.type) { + DocumentChange.Type.ADDED -> Log.d(TAG, "New city: ${dc.document.data}") + DocumentChange.Type.MODIFIED -> Log.d(TAG, "Modified city: ${dc.document.data}") + DocumentChange.Type.REMOVED -> Log.d(TAG, "Removed city: ${dc.document.data}") } } + } // [END listen_diffs] } private fun listenState() { // [START listen_state] db.collection("cities") - .whereEqualTo("state", "CA") - .addSnapshotListener { snapshots, e -> - if (e != null) { - Log.w(TAG, "listen:error", e) - return@addSnapshotListener - } + .whereEqualTo("state", "CA") + .addSnapshotListener { snapshots, e -> + if (e != null) { + Log.w(TAG, "listen:error", e) + return@addSnapshotListener + } - for (dc in snapshots!!.documentChanges) { - if (dc.type == DocumentChange.Type.ADDED) { - Log.d(TAG, "New city: ${dc.document.data}") - } + for (dc in snapshots!!.documentChanges) { + if (dc.type == DocumentChange.Type.ADDED) { + Log.d(TAG, "New city: ${dc.document.data}") } + } - if (!snapshots.metadata.isFromCache) { - Log.d(TAG, "Got initial state.") - } + if (!snapshots.metadata.isFromCache) { + Log.d(TAG, "Got initial state.") } + } // [END listen_state] } @@ -669,18 +676,18 @@ abstract class DocSnippets(val db: FirebaseFirestore) { private fun handleListenErrors() { // [START handle_listen_errors] db.collection("cities") - .addSnapshotListener { snapshots, e -> - if (e != null) { - Log.w(TAG, "listen:error", e) - return@addSnapshotListener - } + .addSnapshotListener { snapshots, e -> + if (e != null) { + Log.w(TAG, "listen:error", e) + return@addSnapshotListener + } - for (dc in snapshots!!.documentChanges) { - if (dc.type == DocumentChange.Type.ADDED) { - Log.d(TAG, "New city: ${dc.document.data}") - } + for (dc in snapshots!!.documentChanges) { + if (dc.type == DocumentChange.Type.ADDED) { + Log.d(TAG, "New city: ${dc.document.data}") } } + } // [END handle_listen_errors] } @@ -689,52 +696,52 @@ abstract class DocSnippets(val db: FirebaseFirestore) { val cities = db.collection("cities") val data1 = hashMapOf( - "name" to "San Francisco", - "state" to "CA", - "country" to "USA", - "capital" to false, - "population" to 860000, - "regions" to listOf("west_coast", "norcal") + "name" to "San Francisco", + "state" to "CA", + "country" to "USA", + "capital" to false, + "population" to 860000, + "regions" to listOf("west_coast", "norcal"), ) cities.document("SF").set(data1) val data2 = hashMapOf( - "name" to "Los Angeles", - "state" to "CA", - "country" to "USA", - "capital" to false, - "population" to 3900000, - "regions" to listOf("west_coast", "socal") + "name" to "Los Angeles", + "state" to "CA", + "country" to "USA", + "capital" to false, + "population" to 3900000, + "regions" to listOf("west_coast", "socal"), ) cities.document("LA").set(data2) val data3 = hashMapOf( - "name" to "Washington D.C.", - "state" to null, - "country" to "USA", - "capital" to true, - "population" to 680000, - "regions" to listOf("east_coast") + "name" to "Washington D.C.", + "state" to null, + "country" to "USA", + "capital" to true, + "population" to 680000, + "regions" to listOf("east_coast"), ) cities.document("DC").set(data3) val data4 = hashMapOf( - "name" to "Tokyo", - "state" to null, - "country" to "Japan", - "capital" to true, - "population" to 9000000, - "regions" to listOf("kanto", "honshu") + "name" to "Tokyo", + "state" to null, + "country" to "Japan", + "capital" to true, + "population" to 9000000, + "regions" to listOf("kanto", "honshu"), ) cities.document("TOK").set(data4) val data5 = hashMapOf( - "name" to "Beijing", - "state" to null, - "country" to "China", - "capital" to true, - "population" to 21500000, - "regions" to listOf("jingjinji", "hebei") + "name" to "Beijing", + "state" to null, + "country" to "China", + "capital" to true, + "population" to 21500000, + "regions" to listOf("jingjinji", "hebei"), ) cities.document("BJ").set(data5) // [END example_data] @@ -745,62 +752,62 @@ abstract class DocSnippets(val db: FirebaseFirestore) { val citiesRef = db.collection("cities") val ggbData = mapOf( - "name" to "Golden Gate Bridge", - "type" to "bridge" + "name" to "Golden Gate Bridge", + "type" to "bridge", ) citiesRef.document("SF").collection("landmarks").add(ggbData) val lohData = mapOf( - "name" to "Legion of Honor", - "type" to "museum" + "name" to "Legion of Honor", + "type" to "museum", ) citiesRef.document("SF").collection("landmarks").add(lohData) val gpData = mapOf( - "name" to "Griffth Park", - "type" to "park" + "name" to "Griffth Park", + "type" to "park", ) citiesRef.document("LA").collection("landmarks").add(gpData) val tgData = mapOf( - "name" to "The Getty", - "type" to "museum" + "name" to "The Getty", + "type" to "museum", ) citiesRef.document("LA").collection("landmarks").add(tgData) val lmData = mapOf( - "name" to "Lincoln Memorial", - "type" to "memorial" + "name" to "Lincoln Memorial", + "type" to "memorial", ) citiesRef.document("DC").collection("landmarks").add(lmData) val nasaData = mapOf( - "name" to "National Air and Space Museum", - "type" to "museum" + "name" to "National Air and Space Museum", + "type" to "museum", ) citiesRef.document("DC").collection("landmarks").add(nasaData) val upData = mapOf( - "name" to "Ueno Park", - "type" to "park" + "name" to "Ueno Park", + "type" to "park", ) citiesRef.document("TOK").collection("landmarks").add(upData) val nmData = mapOf( - "name" to "National Musuem of Nature and Science", - "type" to "museum" + "name" to "National Musuem of Nature and Science", + "type" to "museum", ) citiesRef.document("TOK").collection("landmarks").add(nmData) val jpData = mapOf( - "name" to "Jingshan Park", - "type" to "park" + "name" to "Jingshan Park", + "type" to "park", ) citiesRef.document("BJ").collection("landmarks").add(jpData) val baoData = mapOf( - "name" to "Beijing Ancient Observatory", - "type" to "musuem" + "name" to "Beijing Ancient Observatory", + "type" to "musuem", ) citiesRef.document("BJ").collection("landmarks").add(baoData) // [END fs_collection_group_query_data_setup] @@ -872,9 +879,9 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // [START valid_range_filters] citiesRef.whereGreaterThanOrEqualTo("state", "CA") - .whereLessThanOrEqualTo("state", "IN") + .whereLessThanOrEqualTo("state", "IN") citiesRef.whereEqualTo("state", "CA") - .whereGreaterThan("population", 1000000) + .whereGreaterThan("population", 1000000) // [END valid_range_filters] } @@ -883,7 +890,7 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // [START invalid_range_filters] citiesRef.whereGreaterThanOrEqualTo("state", "CA") - .whereGreaterThan("population", 100000) + .whereGreaterThan("population", 100000) // [END invalid_range_filters] } @@ -923,81 +930,81 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // [START query_start_at_single] // Get all cities with a population >= 1,000,000, ordered by population, db.collection("cities") - .orderBy("population") - .startAt(1000000) + .orderBy("population") + .startAt(1000000) // [END query_start_at_single] // [START query_end_at_single] // Get all cities with a population <= 1,000,000, ordered by population, db.collection("cities") - .orderBy("population") - .endAt(1000000) + .orderBy("population") + .endAt(1000000) // [END query_end_at_single] // [START query_start_at_doc_snapshot] // Get the data for "San Francisco" db.collection("cities").document("SF") - .get() - .addOnSuccessListener { documentSnapshot -> - // Get all cities with a population bigger than San Francisco. - val biggerThanSf = db.collection("cities") - .orderBy("population") - .startAt(documentSnapshot) - - // ... - } + .get() + .addOnSuccessListener { documentSnapshot -> + // Get all cities with a population bigger than San Francisco. + val biggerThanSf = db.collection("cities") + .orderBy("population") + .startAt(documentSnapshot) + + // ... + } // [END query_start_at_doc_snapshot] // [START query_pagination] // Construct query for first 25 cities, ordered by population val first = db.collection("cities") - .orderBy("population") - .limit(25) + .orderBy("population") + .limit(25) first.get() - .addOnSuccessListener { documentSnapshots -> - // ... + .addOnSuccessListener { documentSnapshots -> + // ... - // Get the last visible document - val lastVisible = documentSnapshots.documents[documentSnapshots.size() - 1] + // Get the last visible document + val lastVisible = documentSnapshots.documents[documentSnapshots.size() - 1] - // Construct a new query starting at this document, - // get the next 25 cities. - val next = db.collection("cities") - .orderBy("population") - .startAfter(lastVisible) - .limit(25) + // Construct a new query starting at this document, + // get the next 25 cities. + val next = db.collection("cities") + .orderBy("population") + .startAfter(lastVisible) + .limit(25) - // Use the query for pagination - // ... - } + // Use the query for pagination + // ... + } // [END query_pagination] // [START multi_cursor] // Will return all Springfields db.collection("cities") - .orderBy("name") - .orderBy("state") - .startAt("Springfield") + .orderBy("name") + .orderBy("state") + .startAt("Springfield") // Will return "Springfield, Missouri" and "Springfield, Wisconsin" db.collection("cities") - .orderBy("name") - .orderBy("state") - .startAt("Springfield", "Missouri") + .orderBy("name") + .orderBy("state") + .startAt("Springfield", "Missouri") // [END multi_cursor] } private fun collectionGroupQuery() { // [START fs_collection_group_query] db.collectionGroup("landmarks").whereEqualTo("type", "museum").get() - .addOnSuccessListener { queryDocumentSnapshots -> - // [START_EXCLUDE] - for (snap in queryDocumentSnapshots) { - Log.d(TAG, "${snap.id} => ${snap.data}") - } - // [END_EXCLUDE] + .addOnSuccessListener { queryDocumentSnapshots -> + // [START_EXCLUDE] + for (snap in queryDocumentSnapshots) { + Log.d(TAG, "${snap.id} => ${snap.data}") } + // [END_EXCLUDE] + } // [END fs_collection_group_query] } @@ -1020,24 +1027,25 @@ abstract class DocSnippets(val db: FirebaseFirestore) { fun offlineListen(db: FirebaseFirestore) { // [START offline_listen] db.collection("cities").whereEqualTo("state", "CA") - .addSnapshotListener(MetadataChanges.INCLUDE) { querySnapshot, e -> - if (e != null) { - Log.w(TAG, "Listen error", e) - return@addSnapshotListener - } + .addSnapshotListener(MetadataChanges.INCLUDE) { querySnapshot, e -> + if (e != null) { + Log.w(TAG, "Listen error", e) + return@addSnapshotListener + } - for (change in querySnapshot!!.documentChanges) { - if (change.type == DocumentChange.Type.ADDED) { - Log.d(TAG, "New city: ${change.document.data}") - } + for (change in querySnapshot!!.documentChanges) { + if (change.type == DocumentChange.Type.ADDED) { + Log.d(TAG, "New city: ${change.document.data}") + } - val source = if (querySnapshot.metadata.isFromCache) - "local cache" - else - "server" - Log.d(TAG, "Data fetched from $source") + val source = if (querySnapshot.metadata.isFromCache) { + "local cache" + } else { + "server" } + Log.d(TAG, "Data fetched from $source") } + } // [END offline_listen] } @@ -1045,6 +1053,7 @@ abstract class DocSnippets(val db: FirebaseFirestore) { inner class MyObject { var name: String? = null + @ServerTimestamp var timestamp: Date? = null } @@ -1056,7 +1065,7 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // Update the timestamp field with the value from the server val updates = hashMapOf( - "timestamp" to FieldValue.serverTimestamp() + "timestamp" to FieldValue.serverTimestamp(), ) docRef.update(updates).addOnCompleteListener { } @@ -1069,7 +1078,7 @@ abstract class DocSnippets(val db: FirebaseFirestore) { // Remove the 'capital' field from the document val updates = hashMapOf( - "capital" to FieldValue.delete() + "capital" to FieldValue.delete(), ) docRef.update(updates).addOnCompleteListener { } diff --git a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionAggregation.kt b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionAggregation.kt index 845c7394d..e5a5c808f 100644 --- a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionAggregation.kt +++ b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionAggregation.kt @@ -16,7 +16,7 @@ abstract class SolutionAggregation(private val db: FirebaseFirestore) { // default values required for use with "toObject" internal var name: String = "", internal var avgRating: Double = 0.0, - internal var numRatings: Int = 0 + internal var numRatings: Int = 0, ) // [END restaurant_class] @@ -29,9 +29,9 @@ abstract class SolutionAggregation(private val db: FirebaseFirestore) { fun getAllRatings() { // [START get_all_ratings] db.collection("restaurants") - .document("arinell-pizza") - .collection("ratings") - .get() + .document("arinell-pizza") + .collection("ratings") + .get() // [END get_all_ratings] } @@ -60,7 +60,7 @@ abstract class SolutionAggregation(private val db: FirebaseFirestore) { // Update rating val data = hashMapOf( - "rating" to rating + "rating" to rating, ) transaction.set(ratingRef, data, SetOptions.merge()) diff --git a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionArrays.kt b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionArrays.kt index 69db6795d..e308cb866 100644 --- a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionArrays.kt +++ b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionArrays.kt @@ -21,16 +21,21 @@ abstract class SolutionArrays(private val db: FirebaseFirestore) { fun examplePosts() { // [START example_array_post] - val myArrayPost = ArrayPost("My great post", arrayListOf( - "technology", "opinion", "cats" - )) + val myArrayPost = ArrayPost( + "My great post", + arrayListOf( + "technology", + "opinion", + "cats", + ), + ) // [END example_array_post] // [START example_map_post] val categories = hashMapOf( - "technology" to true, - "opinion" to true, - "cats" to true + "technology" to true, + "opinion" to true, + "cats" to true, ) val myMapPost = MapPost("My great post", categories) // [END example_map_post] @@ -39,9 +44,9 @@ abstract class SolutionArrays(private val db: FirebaseFirestore) { fun examplePosts_Advanced() { // [START example_map_post_advanced] val categories = hashMapOf( - "technology" to 1502144665L, - "opinion" to 1502144665L, - "cats" to 1502144665L + "technology" to 1502144665L, + "opinion" to 1502144665L, + "cats" to 1502144665L, ) val myMapPostAdvanced = MapPostAdvanced("My great post", categories) @@ -51,23 +56,23 @@ abstract class SolutionArrays(private val db: FirebaseFirestore) { fun queryForCats() { // [START query_for_cats] db.collection("posts") - .whereEqualTo("categories.cats", true) - .get() - .addOnCompleteListener { } + .whereEqualTo("categories.cats", true) + .get() + .addOnCompleteListener { } // [END query_for_cats] } fun queryForCatsTimestamp() { // [START query_for_cats_timestamp_invalid] db.collection("posts") - .whereEqualTo("categories.cats", true) - .orderBy("timestamp") + .whereEqualTo("categories.cats", true) + .orderBy("timestamp") // [END query_for_cats_timestamp_invalid] // [START query_for_cats_timestamp] db.collection("posts") - .whereGreaterThan("categories.cats", 0) - .orderBy("categories.cats") + .whereGreaterThan("categories.cats", 0) + .orderBy("categories.cats") // [END query_for_cats_timestamp] } } diff --git a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionBundles.kt b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionBundles.kt index 0a1b411f3..cad75804f 100644 --- a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionBundles.kt +++ b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionBundles.kt @@ -9,7 +9,6 @@ import java.io.InputStream import java.net.HttpURLConnection import java.net.URL - /** * https://firebase.google.com/docs/firestore/solutions/serve-bundles */ diff --git a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionCounters.kt b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionCounters.kt index 1c0504329..dd5bd9d04 100644 --- a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionCounters.kt +++ b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionCounters.kt @@ -24,24 +24,24 @@ class SolutionCounters(val db: FirebaseFirestore) { fun createCounter(ref: DocumentReference, numShards: Int): Task { // Initialize the counter document, then initialize each shard. return ref.set(Counter(numShards)) - .continueWithTask { task -> - if (!task.isSuccessful) { - throw task.exception!! - } - - val tasks = arrayListOf>() + .continueWithTask { task -> + if (!task.isSuccessful) { + throw task.exception!! + } - // Initialize each shard with count=0 - for (i in 0 until numShards) { - val makeShard = ref.collection("shards") - .document(i.toString()) - .set(Shard(0)) + val tasks = arrayListOf>() - tasks.add(makeShard) - } + // Initialize each shard with count=0 + for (i in 0 until numShards) { + val makeShard = ref.collection("shards") + .document(i.toString()) + .set(Shard(0)) - Tasks.whenAll(tasks) + tasks.add(makeShard) } + + Tasks.whenAll(tasks) + } } // [END create_counter] @@ -58,14 +58,14 @@ class SolutionCounters(val db: FirebaseFirestore) { fun getCount(ref: DocumentReference): Task { // Sum the count of each shard in the subcollection return ref.collection("shards").get() - .continueWith { task -> - var count = 0 - for (snap in task.result!!) { - val shard = snap.toObject() - count += shard.count - } - count + .continueWith { task -> + var count = 0 + for (snap in task.result!!) { + val shard = snap.toObject() + count += shard.count } + count + } } // [END get_count] } diff --git a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionDeletes.kt b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionDeletes.kt index 15c34fe19..1e7e9c8c2 100644 --- a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionDeletes.kt +++ b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionDeletes.kt @@ -13,14 +13,14 @@ class SolutionDeletes { fun deleteAtPath(path: String) { val deleteFn = Firebase.functions.getHttpsCallable("recursiveDelete") deleteFn.call(hashMapOf("path" to path)) - .addOnSuccessListener { - // Delete Success - // ... - } - .addOnFailureListener { - // Delete Failed - // ... - } + .addOnSuccessListener { + // Delete Success + // ... + } + .addOnFailureListener { + // Delete Failed + // ... + } } // [END call_delete_function] } diff --git a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionGeoqueries.kt b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionGeoqueries.kt index bb5a816c9..168a5aad3 100644 --- a/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionGeoqueries.kt +++ b/firestore/app/src/main/java/com/google/example/firestore/kotlin/SolutionGeoqueries.kt @@ -24,13 +24,13 @@ class SolutionGeoqueries { val updates: MutableMap = mutableMapOf( "geohash" to hash, "lat" to lat, - "lng" to lng + "lng" to lng, ) val londonRef = db.collection("cities").document("LON") londonRef.update(updates) - .addOnCompleteListener { - // ... - } + .addOnCompleteListener { + // ... + } // [END fs_geo_add_hash] } @@ -47,35 +47,35 @@ class SolutionGeoqueries { val tasks: MutableList> = ArrayList() for (b in bounds) { val q = db.collection("cities") - .orderBy("geohash") - .startAt(b.startHash) - .endAt(b.endHash) + .orderBy("geohash") + .startAt(b.startHash) + .endAt(b.endHash) tasks.add(q.get()) } // Collect all the query results together into a single list Tasks.whenAllComplete(tasks) - .addOnCompleteListener { - val matchingDocs: MutableList = ArrayList() - for (task in tasks) { - val snap = task.result - for (doc in snap!!.documents) { - val lat = doc.getDouble("lat")!! - val lng = doc.getDouble("lng")!! + .addOnCompleteListener { + val matchingDocs: MutableList = ArrayList() + for (task in tasks) { + val snap = task.result + for (doc in snap!!.documents) { + val lat = doc.getDouble("lat")!! + val lng = doc.getDouble("lng")!! - // We have to filter out a few false positives due to GeoHash - // accuracy, but most will match - val docLocation = GeoLocation(lat, lng) - val distanceInM = GeoFireUtils.getDistanceBetween(docLocation, center) - if (distanceInM <= radiusInM) { - matchingDocs.add(doc) - } + // We have to filter out a few false positives due to GeoHash + // accuracy, but most will match + val docLocation = GeoLocation(lat, lng) + val distanceInM = GeoFireUtils.getDistanceBetween(docLocation, center) + if (distanceInM <= radiusInM) { + matchingDocs.add(doc) } } - - // matchingDocs contains the results - // ... } + + // matchingDocs contains the results + // ... + } // [END fs_geo_query_hashes] } } diff --git a/firestore/build.gradle b/firestore/build.gradle index a5f172888..50a990ab5 100644 --- a/firestore/build.gradle +++ b/firestore/build.gradle @@ -9,7 +9,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/functions/app/src/main/java/devrel/firebase/google/com/functions/kotlin/MainActivity.kt b/functions/app/src/main/java/devrel/firebase/google/com/functions/kotlin/MainActivity.kt index 60732a12a..eca608d15 100644 --- a/functions/app/src/main/java/devrel/firebase/google/com/functions/kotlin/MainActivity.kt +++ b/functions/app/src/main/java/devrel/firebase/google/com/functions/kotlin/MainActivity.kt @@ -35,7 +35,7 @@ class MainActivity : AppCompatActivity() { // Create the arguments to the callable function, which are two integers val data = hashMapOf( "firstNumber" to a, - "secondNumber" to b + "secondNumber" to b, ) // Call the function and extract the operation from the result @@ -57,7 +57,7 @@ class MainActivity : AppCompatActivity() { // Create the arguments to the callable function. val data = hashMapOf( "text" to text, - "push" to true + "push" to true, ) return functions @@ -80,7 +80,6 @@ class MainActivity : AppCompatActivity() { if (!task.isSuccessful) { val e = task.exception if (e is FirebaseFunctionsException) { - // Function error code, will be INTERNAL if the failure // was not handled properly in the function call. val code = e.code @@ -94,7 +93,7 @@ class MainActivity : AppCompatActivity() { // [END call_add_numbers] } - private fun callAddMessage(inputMessage: String){ + private fun callAddMessage(inputMessage: String) { // [START call_add_message] addMessage(inputMessage) .addOnCompleteListener { task -> diff --git a/functions/build.gradle b/functions/build.gradle index 302b37ca8..079fc78ec 100644 --- a/functions/build.gradle +++ b/functions/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/inappmessaging/app/src/main/java/com/google/firebase/example/inappmessaging/kotlin/MyClickListenerBundles.kt b/inappmessaging/app/src/main/java/com/google/firebase/example/inappmessaging/kotlin/MyClickListenerBundles.kt index 853d5cf7f..79b828bd8 100644 --- a/inappmessaging/app/src/main/java/com/google/firebase/example/inappmessaging/kotlin/MyClickListenerBundles.kt +++ b/inappmessaging/app/src/main/java/com/google/firebase/example/inappmessaging/kotlin/MyClickListenerBundles.kt @@ -17,4 +17,4 @@ class MyClickListenerBundles : FirebaseInAppMessagingClickListener { // ... } } -// [END fiam_click_listener_bundles] \ No newline at end of file +// [END fiam_click_listener_bundles] diff --git a/inappmessaging/build.gradle b/inappmessaging/build.gradle index 0145c30c5..87591c53d 100644 --- a/inappmessaging/build.gradle +++ b/inappmessaging/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/installations/app/src/main/java/com/google/samples/snippet/kotlin/MainActivity.kt b/installations/app/src/main/java/com/google/samples/snippet/kotlin/MainActivity.kt index 1b5152051..8a4e7f7a3 100644 --- a/installations/app/src/main/java/com/google/samples/snippet/kotlin/MainActivity.kt +++ b/installations/app/src/main/java/com/google/samples/snippet/kotlin/MainActivity.kt @@ -1,8 +1,8 @@ package com.google.samples.snippet.kotlin -import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log +import androidx.appcompat.app.AppCompatActivity import com.google.firebase.installations.FirebaseInstallations import com.google.samples.snippet.R @@ -16,7 +16,8 @@ class MainActivity : AppCompatActivity() { private fun logInstallationAuthToken() { // [START get_installation_token] - FirebaseInstallations.getInstance().getToken(/* forceRefresh */ true) + val forceRefresh = true + FirebaseInstallations.getInstance().getToken(forceRefresh) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d("Installations", "Installation auth token: " + task.result?.token) @@ -44,7 +45,7 @@ class MainActivity : AppCompatActivity() { FirebaseInstallations.getInstance().delete().addOnCompleteListener { task -> if (task.isComplete) { Log.d("Installations", "Installation deleted") - } else { + } else { Log.e("Installations", "Unable to delete Installation") } } diff --git a/installations/build.gradle b/installations/build.gradle index 08bdd98ee..dd7ed5f88 100644 --- a/installations/build.gradle +++ b/installations/build.gradle @@ -7,7 +7,7 @@ buildscript { dependencies { classpath "com.android.tools.build:gradle:8.0.0" classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files diff --git a/messaging/app/src/main/java/com/google/firebase/example/messaging/kotlin/MainActivity.kt b/messaging/app/src/main/java/com/google/firebase/example/messaging/kotlin/MainActivity.kt index 2bc91bc64..41246b08f 100644 --- a/messaging/app/src/main/java/com/google/firebase/example/messaging/kotlin/MainActivity.kt +++ b/messaging/app/src/main/java/com/google/firebase/example/messaging/kotlin/MainActivity.kt @@ -1,29 +1,22 @@ package com.google.firebase.example.messaging.kotlin import android.Manifest -import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts -import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat -import androidx.lifecycle.lifecycleScope -import com.google.firebase.Timestamp -import com.google.firebase.example.messaging.MainActivity import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.google.firebase.messaging.ktx.messaging import com.google.firebase.messaging.ktx.remoteMessage -import java.util.Calendar -import java.util.Date -import java.util.concurrent.atomic.AtomicInteger import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await +import java.util.concurrent.atomic.AtomicInteger class MainActivity : AppCompatActivity() { @@ -54,10 +47,12 @@ class MainActivity : AppCompatActivity() { // [START fcm_device_group_upstream] val to = "a_unique_key" // the notification key val msgId = AtomicInteger() - Firebase.messaging.send(remoteMessage(to) { - setMessageId(msgId.get().toString()) - addData("hello", "world") - }) + Firebase.messaging.send( + remoteMessage(to) { + setMessageId(msgId.get().toString()) + addData("hello", "world") + }, + ) // [END fcm_device_group_upstream] } @@ -66,11 +61,13 @@ class MainActivity : AppCompatActivity() { val messageId = 0 // Increment for each // [START fcm_send_upstream] val fm = Firebase.messaging - fm.send(remoteMessage("$SENDER_ID@fcm.googleapis.com") { - setMessageId(messageId.toString()) - addData("my_message", "Hello World") - addData("my_action", "SAY_HELLO") - }) + fm.send( + remoteMessage("$SENDER_ID@fcm.googleapis.com") { + setMessageId(messageId.toString()) + addData("my_message", "Hello World") + addData("my_action", "SAY_HELLO") + }, + ) // [END fcm_send_upstream] } @@ -110,7 +107,7 @@ class MainActivity : AppCompatActivity() { // [START ask_post_notifications] // Declare the launcher at the top of your Activity/Fragment: private val requestPermissionLauncher = registerForActivityResult( - ActivityResultContracts.RequestPermission() + ActivityResultContracts.RequestPermission(), ) { isGranted: Boolean -> if (isGranted) { // FCM SDK (and your app) can post notifications. @@ -154,5 +151,4 @@ class MainActivity : AppCompatActivity() { return token } // [END get_store_token] - } diff --git a/messaging/app/src/main/java/com/google/firebase/example/messaging/kotlin/MyFirebaseMessagingService.kt b/messaging/app/src/main/java/com/google/firebase/example/messaging/kotlin/MyFirebaseMessagingService.kt index 970192563..da8dce39a 100644 --- a/messaging/app/src/main/java/com/google/firebase/example/messaging/kotlin/MyFirebaseMessagingService.kt +++ b/messaging/app/src/main/java/com/google/firebase/example/messaging/kotlin/MyFirebaseMessagingService.kt @@ -13,7 +13,6 @@ import androidx.work.OneTimeWorkRequest import androidx.work.WorkManager import androidx.work.Worker import androidx.work.WorkerParameters -import com.google.firebase.example.messaging.R import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage @@ -29,7 +28,8 @@ class MyFirebaseMessagingService : FirebaseMessagingService() { if (remoteMessage.data.isNotEmpty()) { Log.d(TAG, "Message data payload: ${remoteMessage.data}") - if (/* Check if data needs to be processed by long running job */ true) { + // Check if data needs to be processed by long running job + if (needsToBeScheduled()) { // For long-running tasks (10 seconds or more) use WorkManager. scheduleJob() } else { @@ -48,6 +48,8 @@ class MyFirebaseMessagingService : FirebaseMessagingService() { } // [END receive_message] + private fun needsToBeScheduled() = true + // [START on_new_token] /** * Called if the FCM registration token is updated. This may occur if the security of @@ -86,8 +88,13 @@ class MyFirebaseMessagingService : FirebaseMessagingService() { private fun sendNotification(messageBody: String) { val intent = Intent(this, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) - val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, - PendingIntent.FLAG_IMMUTABLE) + val requestCode = 0 + val pendingIntent = PendingIntent.getActivity( + this, + requestCode, + intent, + PendingIntent.FLAG_IMMUTABLE, + ) val channelId = "fcm_default_channel" val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) @@ -102,13 +109,16 @@ class MyFirebaseMessagingService : FirebaseMessagingService() { // Since android Oreo notification channel is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - val channel = NotificationChannel(channelId, + val channel = NotificationChannel( + channelId, "Channel human readable title", - NotificationManager.IMPORTANCE_DEFAULT) + NotificationManager.IMPORTANCE_DEFAULT, + ) notificationManager.createNotificationChannel(channel) } - notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()) + val notificationId = 0 + notificationManager.notify(notificationId, notificationBuilder.build()) } companion object { @@ -121,4 +131,4 @@ class MyFirebaseMessagingService : FirebaseMessagingService() { return Result.success() } } -} \ No newline at end of file +} diff --git a/messaging/build.gradle b/messaging/build.gradle index 0145c30c5..87591c53d 100644 --- a/messaging/build.gradle +++ b/messaging/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/ml-functions/app/src/main/java/devrel/firebase/google/com/mlfunctions/kotlin/MainActivity.kt b/ml-functions/app/src/main/java/devrel/firebase/google/com/mlfunctions/kotlin/MainActivity.kt index 28e3c0d67..f06255414 100644 --- a/ml-functions/app/src/main/java/devrel/firebase/google/com/mlfunctions/kotlin/MainActivity.kt +++ b/ml-functions/app/src/main/java/devrel/firebase/google/com/mlfunctions/kotlin/MainActivity.kt @@ -16,11 +16,12 @@ import com.google.gson.JsonParser import com.google.gson.JsonPrimitive import java.io.ByteArrayOutputStream - class MainActivity : AppCompatActivity() { - val uri = null; + val uri = null + // [START function_bitmap] var bitmap: Bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri) + // [END function_bitmap] private lateinit var functions: FirebaseFunctions @@ -51,11 +52,11 @@ class MainActivity : AppCompatActivity() { if (originalHeight > originalWidth) { resizedHeight = maxDimension resizedWidth = - (resizedHeight * originalWidth.toFloat() / originalHeight.toFloat()).toInt() + (resizedHeight * originalWidth.toFloat() / originalHeight.toFloat()).toInt() } else if (originalWidth > originalHeight) { resizedWidth = maxDimension resizedHeight = - (resizedWidth * originalHeight.toFloat() / originalWidth.toFloat()).toInt() + (resizedWidth * originalHeight.toFloat() / originalWidth.toFloat()).toInt() } else if (originalHeight == originalWidth) { resizedHeight = maxDimension resizedWidth = maxDimension @@ -67,15 +68,15 @@ class MainActivity : AppCompatActivity() { // [START function_annotateImage] private fun annotateImage(requestJson: String): Task { return functions - .getHttpsCallable("annotateImage") - .call(requestJson) - .continueWith { task -> - // This continuation runs on either success or failure, but if the task - // has failed then result will throw an Exception which will be - // propagated down. - val result = task.result?.data - JsonParser.parseString(Gson().toJson(result)) - } + .getHttpsCallable("annotateImage") + .call(requestJson) + .continueWith { task -> + // This continuation runs on either success or failure, but if the task + // has failed then result will throw an Exception which will be + // propagated down. + val result = task.result?.data + JsonParser.parseString(Gson().toJson(result)) + } } // [END function_annotateImage] @@ -87,7 +88,7 @@ class MainActivity : AppCompatActivity() { val image = JsonObject() image.add("content", JsonPrimitive(base64encoded)) request.add("image", image) - //Add features to the request + // Add features to the request val feature = JsonObject() feature.add("maxResults", JsonPrimitive(5)) feature.add("type", JsonPrimitive("LABEL_DETECTION")) @@ -105,7 +106,7 @@ class MainActivity : AppCompatActivity() { val image = JsonObject() image.add("content", JsonPrimitive(base64encoded)) request.add("image", image) - //Add features to the request + // Add features to the request val feature = JsonObject() feature.add("maxResults", JsonPrimitive(5)) feature.add("type", JsonPrimitive("LANDMARK_DETECTION")) @@ -123,7 +124,7 @@ class MainActivity : AppCompatActivity() { val image = JsonObject() image.add("content", JsonPrimitive(base64encoded)) request.add("image", image) - //Add features to the request + // Add features to the request val feature = JsonObject() feature.add("type", JsonPrimitive("TEXT_DETECTION")) // Alternatively, for DOCUMENT_TEXT_DETECTION: @@ -145,15 +146,15 @@ class MainActivity : AppCompatActivity() { private fun annotateImage(request: JsonObject) { // [START function_callAnnotate] annotateImage(request.toString()) - .addOnCompleteListener { task -> - if (!task.isSuccessful) { - // Task failed with an exception - // ... - } else { - // Task completed successfully - // ... - } + .addOnCompleteListener { task -> + if (!task.isSuccessful) { + // Task failed with an exception + // ... + } else { + // Task completed successfully + // ... } + } // [END function_callAnnotate] } @@ -178,7 +179,7 @@ class MainActivity : AppCompatActivity() { val bounds = labelObj["boundingPoly"] // Multiple locations are possible, e.g., the location of the depicted // landmark and the location the picture was taken. - for(loc in labelObj["locations"].asJsonArray) { + for (loc in labelObj["locations"].asJsonArray) { val latitude = loc.asJsonObject["latLng"].asJsonObject["latitude"] val longitude = loc.asJsonObject["latLng"].asJsonObject["longitude"] } @@ -204,11 +205,17 @@ class MainActivity : AppCompatActivity() { var wordText = "" for (symbol in word.asJsonObject["symbols"].asJsonArray) { wordText += symbol.asJsonObject["text"].asString - System.out.format("Symbol text: %s (confidence: %f)%n", - symbol.asJsonObject["text"].asString, symbol.asJsonObject["confidence"].asFloat) + System.out.format( + "Symbol text: %s (confidence: %f)%n", + symbol.asJsonObject["text"].asString, + symbol.asJsonObject["confidence"].asFloat, + ) } - System.out.format("Word text: %s (confidence: %f)%n%n", wordText, - word.asJsonObject["confidence"].asFloat) + System.out.format( + "Word text: %s (confidence: %f)%n%n", + wordText, + word.asJsonObject["confidence"].asFloat, + ) System.out.format("Word bounding box: %s%n", word.asJsonObject["boundingBox"]) paraText = String.format("%s%s ", paraText, wordText) } diff --git a/ml-functions/build.gradle b/ml-functions/build.gradle index 302b37ca8..079fc78ec 100644 --- a/ml-functions/build.gradle +++ b/ml-functions/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/BarcodeScanningActivity.kt b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/BarcodeScanningActivity.kt index 1ac77615d..db4d9a3bf 100644 --- a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/BarcodeScanningActivity.kt +++ b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/BarcodeScanningActivity.kt @@ -11,15 +11,16 @@ class BarcodeScanningActivity : AppCompatActivity() { private fun scanBarcodes(image: FirebaseVisionImage) { // [START set_detector_options] val options = FirebaseVisionBarcodeDetectorOptions.Builder() - .setBarcodeFormats( - FirebaseVisionBarcode.FORMAT_QR_CODE, - FirebaseVisionBarcode.FORMAT_AZTEC) - .build() + .setBarcodeFormats( + FirebaseVisionBarcode.FORMAT_QR_CODE, + FirebaseVisionBarcode.FORMAT_AZTEC, + ) + .build() // [END set_detector_options] // [START get_detector] val detector = FirebaseVision.getInstance() - .visionBarcodeDetector + .visionBarcodeDetector // Or, to specify the formats to recognize: // val detector = FirebaseVision.getInstance() // .getVisionBarcodeDetector(options) @@ -27,37 +28,37 @@ class BarcodeScanningActivity : AppCompatActivity() { // [START fml_run_detector] val result = detector.detectInImage(image) - .addOnSuccessListener { barcodes -> - // Task completed successfully - // [START_EXCLUDE] - // [START get_barcodes] - for (barcode in barcodes) { - val bounds = barcode.boundingBox - val corners = barcode.cornerPoints + .addOnSuccessListener { barcodes -> + // Task completed successfully + // [START_EXCLUDE] + // [START get_barcodes] + for (barcode in barcodes) { + val bounds = barcode.boundingBox + val corners = barcode.cornerPoints - val rawValue = barcode.rawValue + val rawValue = barcode.rawValue - val valueType = barcode.valueType - // See API reference for complete list of supported types - when (valueType) { - FirebaseVisionBarcode.TYPE_WIFI -> { - val ssid = barcode.wifi!!.ssid - val password = barcode.wifi!!.password - val type = barcode.wifi!!.encryptionType - } - FirebaseVisionBarcode.TYPE_URL -> { - val title = barcode.url!!.title - val url = barcode.url!!.url - } + val valueType = barcode.valueType + // See API reference for complete list of supported types + when (valueType) { + FirebaseVisionBarcode.TYPE_WIFI -> { + val ssid = barcode.wifi!!.ssid + val password = barcode.wifi!!.password + val type = barcode.wifi!!.encryptionType + } + FirebaseVisionBarcode.TYPE_URL -> { + val title = barcode.url!!.title + val url = barcode.url!!.url } } - // [END get_barcodes] - // [END_EXCLUDE] - } - .addOnFailureListener { - // Task failed with an exception - // ... } + // [END get_barcodes] + // [END_EXCLUDE] + } + .addOnFailureListener { + // Task failed with an exception + // ... + } // [END fml_run_detector] } } diff --git a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/CustomModelActivity.kt b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/CustomModelActivity.kt index 51e1ce2f2..7e27c9c6e 100644 --- a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/CustomModelActivity.kt +++ b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/CustomModelActivity.kt @@ -4,20 +4,18 @@ package com.google.firebase.example.mlkit.kotlin import android.graphics.Bitmap import android.graphics.Color -import androidx.appcompat.app.AppCompatActivity import android.util.Log -import com.google.android.gms.tasks.OnFailureListener +import androidx.appcompat.app.AppCompatActivity import com.google.firebase.ml.common.FirebaseMLException import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions import com.google.firebase.ml.common.modeldownload.FirebaseModelManager import com.google.firebase.ml.custom.FirebaseCustomLocalModel import com.google.firebase.ml.custom.FirebaseCustomRemoteModel -import com.google.firebase.ml.custom.FirebaseModelInterpreterOptions -import com.google.firebase.ml.custom.FirebaseModelInterpreter +import com.google.firebase.ml.custom.FirebaseModelDataType import com.google.firebase.ml.custom.FirebaseModelInputOutputOptions import com.google.firebase.ml.custom.FirebaseModelInputs -import com.google.firebase.ml.custom.FirebaseModelDataType - +import com.google.firebase.ml.custom.FirebaseModelInterpreter +import com.google.firebase.ml.custom.FirebaseModelInterpreterOptions import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader @@ -25,8 +23,7 @@ import java.io.InputStreamReader class CustomModelActivity : AppCompatActivity() { // This method is just for show - private - val yourInputImage: Bitmap + private val yourInputImage: Bitmap get() = Bitmap.createBitmap(0, 0, Bitmap.Config.ALPHA_8) private fun configureHostedModelSource() { @@ -38,20 +35,20 @@ class CustomModelActivity : AppCompatActivity() { private fun startModelDownloadTask(remoteModel: FirebaseCustomRemoteModel) { // [START mlkit_model_download_task] val conditions = FirebaseModelDownloadConditions.Builder() - .requireWifi() - .build() + .requireWifi() + .build() FirebaseModelManager.getInstance().download(remoteModel, conditions) - .addOnCompleteListener { - // Success. - } + .addOnCompleteListener { + // Success. + } // [END mlkit_model_download_task] } private fun configureLocalModelSource() { // [START mlkit_local_model_source] val localModel = FirebaseCustomLocalModel.Builder() - .setAssetFilePath("your_model.tflite") - .build() + .setAssetFilePath("your_model.tflite") + .build() // [END mlkit_local_model_source] } @@ -68,28 +65,28 @@ class CustomModelActivity : AppCompatActivity() { private fun checkModelDownloadStatus(remoteModel: FirebaseCustomRemoteModel, localModel: FirebaseCustomLocalModel) { // [START mlkit_check_download_status] FirebaseModelManager.getInstance().isModelDownloaded(remoteModel) - .addOnSuccessListener { isDownloaded -> - val options = - if (isDownloaded) { - FirebaseModelInterpreterOptions.Builder(remoteModel).build() - } else { - FirebaseModelInterpreterOptions.Builder(localModel).build() - } - val interpreter = FirebaseModelInterpreter.getInstance(options) - } + .addOnSuccessListener { isDownloaded -> + val options = + if (isDownloaded) { + FirebaseModelInterpreterOptions.Builder(remoteModel).build() + } else { + FirebaseModelInterpreterOptions.Builder(localModel).build() + } + val interpreter = FirebaseModelInterpreter.getInstance(options) + } // [END mlkit_check_download_status] } private fun addDownloadListener( - remoteModel: FirebaseCustomRemoteModel, - conditions: FirebaseModelDownloadConditions + remoteModel: FirebaseCustomRemoteModel, + conditions: FirebaseModelDownloadConditions, ) { // [START mlkit_remote_model_download_listener] FirebaseModelManager.getInstance().download(remoteModel, conditions) - .addOnCompleteListener { - // Download complete. Depending on your app, you could enable the ML - // feature, or switch from the local model to the remote model, etc. - } + .addOnCompleteListener { + // Download complete. Depending on your app, you could enable the ML + // feature, or switch from the local model to the remote model, etc. + } // [END mlkit_remote_model_download_listener] } @@ -97,9 +94,9 @@ class CustomModelActivity : AppCompatActivity() { private fun createInputOutputOptions(): FirebaseModelInputOutputOptions { // [START mlkit_create_io_options] val inputOutputOptions = FirebaseModelInputOutputOptions.Builder() - .setInputFormat(0, FirebaseModelDataType.FLOAT32, intArrayOf(1, 224, 224, 3)) - .setOutputFormat(0, FirebaseModelDataType.FLOAT32, intArrayOf(1, 5)) - .build() + .setInputFormat(0, FirebaseModelDataType.FLOAT32, intArrayOf(1, 224, 224, 3)) + .setOutputFormat(0, FirebaseModelDataType.FLOAT32, intArrayOf(1, 5)) + .build() // [END mlkit_create_io_options] return inputOutputOptions } @@ -134,21 +131,21 @@ class CustomModelActivity : AppCompatActivity() { // [START mlkit_run_inference] val inputs = FirebaseModelInputs.Builder() - .add(input) // add() as many input arrays as your model requires - .build() + .add(input) // add() as many input arrays as your model requires + .build() firebaseInterpreter.run(inputs, inputOutputOptions) - .addOnSuccessListener { result -> - // [START_EXCLUDE] - // [START mlkit_read_result] - val output = result.getOutput>(0) - val probabilities = output[0] - // [END mlkit_read_result] - // [END_EXCLUDE] - } - .addOnFailureListener { e -> - // Task failed with an exception - // ... - } + .addOnSuccessListener { result -> + // [START_EXCLUDE] + // [START mlkit_read_result] + val output = result.getOutput>(0) + val probabilities = output[0] + // [END mlkit_read_result] + // [END_EXCLUDE] + } + .addOnFailureListener { e -> + // Task failed with an exception + // ... + } // [END mlkit_run_inference] } @@ -156,7 +153,8 @@ class CustomModelActivity : AppCompatActivity() { private fun useInferenceResult(probabilities: FloatArray) { // [START mlkit_use_inference_result] val reader = BufferedReader( - InputStreamReader(assets.open("retrained_labels.txt"))) + InputStreamReader(assets.open("retrained_labels.txt")), + ) for (i in probabilities.indices) { val label = reader.readLine() Log.i("MLKit", String.format("%s: %1.4f", label, probabilities[i])) diff --git a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/FaceDetectionActivity.kt b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/FaceDetectionActivity.kt index 4adec8246..814ab5e4d 100644 --- a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/FaceDetectionActivity.kt +++ b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/FaceDetectionActivity.kt @@ -1,7 +1,6 @@ package com.google.firebase.example.mlkit.kotlin import androidx.appcompat.app.AppCompatActivity -import com.google.android.gms.tasks.OnFailureListener import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.vision.face.FirebaseVisionFace @@ -14,57 +13,57 @@ class FaceDetectionActivity : AppCompatActivity() { private fun detectFaces(image: FirebaseVisionImage) { // [START set_detector_options] val options = FirebaseVisionFaceDetectorOptions.Builder() - .setClassificationMode(FirebaseVisionFaceDetectorOptions.ACCURATE) - .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS) - .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS) - .setMinFaceSize(0.15f) - .enableTracking() - .build() + .setClassificationMode(FirebaseVisionFaceDetectorOptions.ACCURATE) + .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS) + .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS) + .setMinFaceSize(0.15f) + .enableTracking() + .build() // [END set_detector_options] // [START get_detector] val detector = FirebaseVision.getInstance() - .getVisionFaceDetector(options) + .getVisionFaceDetector(options) // [END get_detector] // [START fml_run_detector] val result = detector.detectInImage(image) - .addOnSuccessListener { faces -> - // Task completed successfully - // [START_EXCLUDE] - // [START get_face_info] - for (face in faces) { - val bounds = face.boundingBox - val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees - val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees + .addOnSuccessListener { faces -> + // Task completed successfully + // [START_EXCLUDE] + // [START get_face_info] + for (face in faces) { + val bounds = face.boundingBox + val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees + val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees - // If landmark detection was enabled (mouth, ears, eyes, cheeks, and - // nose available): - val leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR) - leftEar?.let { - val leftEarPos = leftEar.position - } + // If landmark detection was enabled (mouth, ears, eyes, cheeks, and + // nose available): + val leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR) + leftEar?.let { + val leftEarPos = leftEar.position + } - // If classification was enabled: - if (face.smilingProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) { - val smileProb = face.smilingProbability - } - if (face.rightEyeOpenProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) { - val rightEyeOpenProb = face.rightEyeOpenProbability - } + // If classification was enabled: + if (face.smilingProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) { + val smileProb = face.smilingProbability + } + if (face.rightEyeOpenProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) { + val rightEyeOpenProb = face.rightEyeOpenProbability + } - // If face tracking was enabled: - if (face.trackingId != FirebaseVisionFace.INVALID_ID) { - val id = face.trackingId - } + // If face tracking was enabled: + if (face.trackingId != FirebaseVisionFace.INVALID_ID) { + val id = face.trackingId } - // [END get_face_info] - // [END_EXCLUDE] - } - .addOnFailureListener { e -> - // Task failed with an exception - // ... } + // [END get_face_info] + // [END_EXCLUDE] + } + .addOnFailureListener { e -> + // Task failed with an exception + // ... + } // [END fml_run_detector] } @@ -72,15 +71,15 @@ class FaceDetectionActivity : AppCompatActivity() { // [START mlkit_face_options_examples] // High-accuracy landmark detection and face classification val highAccuracyOpts = FirebaseVisionFaceDetectorOptions.Builder() - .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE) - .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS) - .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS) - .build() + .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE) + .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS) + .setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS) + .build() // Real-time contour detection of multiple faces val realTimeOpts = FirebaseVisionFaceDetectorOptions.Builder() - .setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS) - .build() + .setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS) + .build() // [END mlkit_face_options_examples] } diff --git a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/ImageLabelingActivity.kt b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/ImageLabelingActivity.kt index 6176c88a7..62d9124e6 100644 --- a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/ImageLabelingActivity.kt +++ b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/ImageLabelingActivity.kt @@ -1,12 +1,9 @@ package com.google.firebase.example.mlkit.kotlin import androidx.appcompat.app.AppCompatActivity -import com.google.android.gms.tasks.OnFailureListener -import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions import com.google.firebase.ml.vision.common.FirebaseVisionImage -import com.google.firebase.ml.vision.label.FirebaseVisionImageLabel import com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceImageLabelerOptions class ImageLabelingActivity : AppCompatActivity() { @@ -14,13 +11,13 @@ class ImageLabelingActivity : AppCompatActivity() { private fun labelImages(image: FirebaseVisionImage) { // [START set_detector_options] val options = FirebaseVisionOnDeviceImageLabelerOptions.Builder() - .setConfidenceThreshold(0.8f) - .build() + .setConfidenceThreshold(0.8f) + .build() // [END set_detector_options] // [START get_detector_default] val detector = FirebaseVision.getInstance() - .onDeviceImageLabeler + .onDeviceImageLabeler // [END get_detector_default] /* @@ -29,40 +26,40 @@ class ImageLabelingActivity : AppCompatActivity() { val detector = FirebaseVision.getInstance() .getOnDeviceImageLabeler(options) // [END get_detector_options] - */ + */ // [START fml_run_detector] val result = detector.processImage(image) - .addOnSuccessListener { labels -> - // Task completed successfully - // [START_EXCLUDE] - // [START get_labels] - for (label in labels) { - val text = label.text - val entityId = label.entityId - val confidence = label.confidence - } - // [END get_labels] - // [END_EXCLUDE] - } - .addOnFailureListener { e -> - // Task failed with an exception - // ... + .addOnSuccessListener { labels -> + // Task completed successfully + // [START_EXCLUDE] + // [START get_labels] + for (label in labels) { + val text = label.text + val entityId = label.entityId + val confidence = label.confidence } + // [END get_labels] + // [END_EXCLUDE] + } + .addOnFailureListener { e -> + // Task failed with an exception + // ... + } // [END fml_run_detector] } private fun labelImagesCloud(image: FirebaseVisionImage) { // [START set_detector_options_cloud] val options = FirebaseVisionCloudDetectorOptions.Builder() - .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL) - .setMaxResults(30) - .build() + .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL) + .setMaxResults(30) + .build() // [END set_detector_options_cloud] // [START get_detector_cloud] val detector = FirebaseVision.getInstance() - .cloudImageLabeler + .cloudImageLabeler // Or, to change the default settings: // val detector = FirebaseVision.getInstance() // .getCloudImageLabeler(options) @@ -70,22 +67,22 @@ class ImageLabelingActivity : AppCompatActivity() { // [START fml_run_detector_cloud] val result = detector.processImage(image) - .addOnSuccessListener { labels -> - // Task completed successfully - // [START_EXCLUDE] - // [START get_labels_cloud] - for (label in labels) { - val text = label.text - val entityId = label.entityId - val confidence = label.confidence - } - // [END get_labels_cloud] - // [END_EXCLUDE] - } - .addOnFailureListener { e -> - // Task failed with an exception - // ... + .addOnSuccessListener { labels -> + // Task completed successfully + // [START_EXCLUDE] + // [START get_labels_cloud] + for (label in labels) { + val text = label.text + val entityId = label.entityId + val confidence = label.confidence } + // [END get_labels_cloud] + // [END_EXCLUDE] + } + .addOnFailureListener { e -> + // Task failed with an exception + // ... + } // [END fml_run_detector_cloud] } } diff --git a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/LandmarkRecognitionActivity.kt b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/LandmarkRecognitionActivity.kt index a83cc81f0..d772d5365 100644 --- a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/LandmarkRecognitionActivity.kt +++ b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/LandmarkRecognitionActivity.kt @@ -10,14 +10,14 @@ class LandmarkRecognitionActivity : AppCompatActivity() { private fun recognizeLandmarksCloud(image: FirebaseVisionImage) { // [START set_detector_options_cloud] val options = FirebaseVisionCloudDetectorOptions.Builder() - .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL) - .setMaxResults(30) - .build() + .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL) + .setMaxResults(30) + .build() // [END set_detector_options_cloud] // [START get_detector_cloud] val detector = FirebaseVision.getInstance() - .visionCloudLandmarkDetector + .visionCloudLandmarkDetector // Or, to change the default settings: // val detector = FirebaseVision.getInstance() // .getVisionCloudLandmarkDetector(options) @@ -25,31 +25,30 @@ class LandmarkRecognitionActivity : AppCompatActivity() { // [START fml_run_detector_cloud] val result = detector.detectInImage(image) - .addOnSuccessListener { firebaseVisionCloudLandmarks -> - // Task completed successfully - // [START_EXCLUDE] - // [START get_landmarks_cloud] - for (landmark in firebaseVisionCloudLandmarks) { + .addOnSuccessListener { firebaseVisionCloudLandmarks -> + // Task completed successfully + // [START_EXCLUDE] + // [START get_landmarks_cloud] + for (landmark in firebaseVisionCloudLandmarks) { + val bounds = landmark.boundingBox + val landmarkName = landmark.landmark + val entityId = landmark.entityId + val confidence = landmark.confidence - val bounds = landmark.boundingBox - val landmarkName = landmark.landmark - val entityId = landmark.entityId - val confidence = landmark.confidence - - // Multiple locations are possible, e.g., the location of the depicted - // landmark and the location the picture was taken. - for (loc in landmark.locations) { - val latitude = loc.latitude - val longitude = loc.longitude - } + // Multiple locations are possible, e.g., the location of the depicted + // landmark and the location the picture was taken. + for (loc in landmark.locations) { + val latitude = loc.latitude + val longitude = loc.longitude } - // [END get_landmarks_cloud] - // [END_EXCLUDE] - } - .addOnFailureListener { e -> - // Task failed with an exception - // ... } + // [END get_landmarks_cloud] + // [END_EXCLUDE] + } + .addOnFailureListener { e -> + // Task failed with an exception + // ... + } // [END fml_run_detector_cloud] } } diff --git a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/MainActivity.kt b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/MainActivity.kt index 879b51250..bd08aceec 100644 --- a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/MainActivity.kt +++ b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/MainActivity.kt @@ -13,16 +13,18 @@ class MainActivity : AppCompatActivity() { fun buildCloudVisionOptions() { // [START ml_build_cloud_vision_options] val options = FirebaseVisionCloudDetectorOptions.Builder() - .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL) - .setMaxResults(15) - .build() + .setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL) + .setMaxResults(15) + .build() // [END ml_build_cloud_vision_options] } fun enforceCertificateMatching() { // Dummy variable - val myImage = FirebaseVisionImage.fromByteArray(byteArrayOf(), - FirebaseVisionImageMetadata.Builder().build()) + val myImage = FirebaseVisionImage.fromByteArray( + byteArrayOf(), + FirebaseVisionImageMetadata.Builder().build(), + ) // [START mlkit_certificate_matching] val optionsBuilder = FirebaseVisionCloudImageLabelerOptions.Builder() diff --git a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/TextRecognitionActivity.kt b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/TextRecognitionActivity.kt index fdb3277ca..ad116cb2a 100644 --- a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/TextRecognitionActivity.kt +++ b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/TextRecognitionActivity.kt @@ -9,50 +9,48 @@ import com.google.firebase.ml.vision.document.FirebaseVisionDocumentText import com.google.firebase.ml.vision.document.FirebaseVisionDocumentTextRecognizer import com.google.firebase.ml.vision.text.FirebaseVisionCloudTextRecognizerOptions import com.google.firebase.ml.vision.text.FirebaseVisionText -import java.util.Arrays class TextRecognitionActivity : AppCompatActivity() { private fun recognizeText(image: FirebaseVisionImage) { - // [START get_detector_default] val detector = FirebaseVision.getInstance() - .onDeviceTextRecognizer + .onDeviceTextRecognizer // [END get_detector_default] // [START fml_run_detector] val result = detector.processImage(image) - .addOnSuccessListener { firebaseVisionText -> - // Task completed successfully - // [START_EXCLUDE] - // [START get_text] - for (block in firebaseVisionText.textBlocks) { - val boundingBox = block.boundingBox - val cornerPoints = block.cornerPoints - val text = block.text - - for (line in block.lines) { + .addOnSuccessListener { firebaseVisionText -> + // Task completed successfully + // [START_EXCLUDE] + // [START get_text] + for (block in firebaseVisionText.textBlocks) { + val boundingBox = block.boundingBox + val cornerPoints = block.cornerPoints + val text = block.text + + for (line in block.lines) { + // ... + for (element in line.elements) { // ... - for (element in line.elements) { - // ... - } } } - // [END get_text] - // [END_EXCLUDE] - } - .addOnFailureListener { e -> - // Task failed with an exception - // ... } + // [END get_text] + // [END_EXCLUDE] + } + .addOnFailureListener { e -> + // Task failed with an exception + // ... + } // [END fml_run_detector] } private fun recognizeTextCloud(image: FirebaseVisionImage) { // [START set_detector_options_cloud] val options = FirebaseVisionCloudTextRecognizerOptions.Builder() - .setLanguageHints(listOf("en", "hi")) - .build() + .setLanguageHints(listOf("en", "hi")) + .build() // [END set_detector_options_cloud] // [START get_detector_cloud] @@ -63,29 +61,29 @@ class TextRecognitionActivity : AppCompatActivity() { // [START fml_run_detector_cloud] val result = detector.processImage(image) - .addOnSuccessListener { firebaseVisionText -> - // Task completed successfully - // [START_EXCLUDE] - // [START get_text_cloud] - for (block in firebaseVisionText.textBlocks) { - val boundingBox = block.boundingBox - val cornerPoints = block.cornerPoints - val text = block.text - - for (line in block.lines) { + .addOnSuccessListener { firebaseVisionText -> + // Task completed successfully + // [START_EXCLUDE] + // [START get_text_cloud] + for (block in firebaseVisionText.textBlocks) { + val boundingBox = block.boundingBox + val cornerPoints = block.cornerPoints + val text = block.text + + for (line in block.lines) { + // ... + for (element in line.elements) { // ... - for (element in line.elements) { - // ... - } } } - // [END get_text_cloud] - // [END_EXCLUDE] - } - .addOnFailureListener { e -> - // Task failed with an exception - // ... } + // [END get_text_cloud] + // [END_EXCLUDE] + } + .addOnFailureListener { e -> + // Task failed with an exception + // ... + } // [END fml_run_detector_cloud] } @@ -119,7 +117,7 @@ class TextRecognitionActivity : AppCompatActivity() { private fun getLocalDocumentRecognizer(): FirebaseVisionDocumentTextRecognizer { // [START mlkit_local_doc_recognizer] val detector = FirebaseVision.getInstance() - .cloudDocumentTextRecognizer + .cloudDocumentTextRecognizer // [END mlkit_local_doc_recognizer] return detector @@ -130,10 +128,10 @@ class TextRecognitionActivity : AppCompatActivity() { // Or, to provide language hints to assist with language detection: // See https://cloud.google.com/vision/docs/languages for supported languages val options = FirebaseVisionCloudDocumentRecognizerOptions.Builder() - .setLanguageHints(listOf("en", "hi")) - .build() + .setLanguageHints(listOf("en", "hi")) + .build() val detector = FirebaseVision.getInstance() - .getCloudDocumentTextRecognizer(options) + .getCloudDocumentTextRecognizer(options) // [END mlkit_cloud_doc_recognizer] return detector @@ -142,19 +140,21 @@ class TextRecognitionActivity : AppCompatActivity() { private fun processDocumentImage() { // Dummy variables val detector = getLocalDocumentRecognizer() - val myImage = FirebaseVisionImage.fromByteArray(byteArrayOf(), - FirebaseVisionImageMetadata.Builder().build()) + val myImage = FirebaseVisionImage.fromByteArray( + byteArrayOf(), + FirebaseVisionImageMetadata.Builder().build(), + ) // [START mlkit_process_doc_image] detector.processImage(myImage) - .addOnSuccessListener { firebaseVisionDocumentText -> - // Task completed successfully - // ... - } - .addOnFailureListener { e -> - // Task failed with an exception - // ... - } + .addOnSuccessListener { firebaseVisionDocumentText -> + // Task completed successfully + // ... + } + .addOnFailureListener { e -> + // Task failed with an exception + // ... + } // [END mlkit_process_doc_image] } diff --git a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/VisionImage.kt b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/VisionImage.kt index f6b1d89dc..1b44b7748 100644 --- a/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/VisionImage.kt +++ b/mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/VisionImage.kt @@ -10,10 +10,10 @@ import android.hardware.camera2.CameraManager import android.media.Image import android.net.Uri import android.os.Build -import androidx.annotation.RequiresApi import android.util.Log import android.util.SparseIntArray import android.view.Surface +import androidx.annotation.RequiresApi import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata import java.io.IOException @@ -37,11 +37,11 @@ class VisionImage { private fun imageFromBuffer(buffer: ByteBuffer, rotation: Int) { // [START set_metadata] val metadata = FirebaseVisionImageMetadata.Builder() - .setWidth(480) // 480x360 is typically sufficient for - .setHeight(360) // image recognition - .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) - .setRotation(rotation) - .build() + .setWidth(480) // 480x360 is typically sufficient for + .setHeight(360) // image recognition + .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) + .setRotation(rotation) + .build() // [END set_metadata] // [START image_from_buffer] val image = FirebaseVisionImage.fromByteBuffer(buffer, metadata) @@ -50,11 +50,11 @@ class VisionImage { private fun imageFromArray(byteArray: ByteArray, rotation: Int) { val metadata = FirebaseVisionImageMetadata.Builder() - .setWidth(480) // 480x360 is typically sufficient for - .setHeight(360) // image recognition - .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) - .setRotation(rotation) - .build() + .setWidth(480) // 480x360 is typically sufficient for + .setHeight(360) // image recognition + .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) + .setRotation(rotation) + .build() // [START image_from_array] val image = FirebaseVisionImage.fromByteArray(byteArray, metadata) // [END image_from_array] @@ -90,8 +90,8 @@ class VisionImage { // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees. val cameraManager = context.getSystemService(CAMERA_SERVICE) as CameraManager val sensorOrientation = cameraManager - .getCameraCharacteristics(cameraId) - .get(CameraCharacteristics.SENSOR_ORIENTATION)!! + .getCameraCharacteristics(cameraId) + .get(CameraCharacteristics.SENSOR_ORIENTATION)!! rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360 // Return the corresponding FirebaseVisionImageMetadata rotation value. diff --git a/mlkit/build.gradle b/mlkit/build.gradle index 0145c30c5..87591c53d 100644 --- a/mlkit/build.gradle +++ b/mlkit/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/perf/app/src/main/java/com/google/firebase/example/perf/kotlin/MainActivity.kt b/perf/app/src/main/java/com/google/firebase/example/perf/kotlin/MainActivity.kt index f99c781be..54e0e0cde 100644 --- a/perf/app/src/main/java/com/google/firebase/example/perf/kotlin/MainActivity.kt +++ b/perf/app/src/main/java/com/google/firebase/example/perf/kotlin/MainActivity.kt @@ -20,7 +20,8 @@ import java.net.URL class MainActivity : AppCompatActivity() { // [START perf_traced_create] - @AddTrace(name = "onCreateTrace", enabled = true /* optional */) + // the `enabled` argument is optional and defaults to true + @AddTrace(name = "onCreateTrace", enabled = true) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } @@ -70,7 +71,7 @@ class MainActivity : AppCompatActivity() { // [START perf_disable_with_config] // Setup remote config val config = Firebase.remoteConfig - + // You can uncomment the following two statements to permit more fetches when // validating your app, but you should comment out or delete these lines before // distributing your app in production. @@ -83,13 +84,13 @@ class MainActivity : AppCompatActivity() { // Observe the remote config parameter "perf_disable" and disable Performance Monitoring if true config.setDefaultsAsync(R.xml.remote_config_defaults) - .addOnCompleteListener { task -> - if (task.isSuccessful) { - Firebase.performance.isPerformanceCollectionEnabled = !config.getBoolean("perf_disable") - } else { - // An error occurred while setting default parameters - } + .addOnCompleteListener { task -> + if (task.isSuccessful) { + Firebase.performance.isPerformanceCollectionEnabled = !config.getBoolean("perf_disable") + } else { + // An error occurred while setting default parameters } + } // [END perf_disable_with_config] } @@ -98,22 +99,22 @@ class MainActivity : AppCompatActivity() { // Remote Config fetches and activates parameter values from the service val config = Firebase.remoteConfig config.fetch(3600) - .continueWithTask { task -> - if (!task.isSuccessful) { - task.exception?.let { - throw it - } + .continueWithTask { task -> + if (!task.isSuccessful) { + task.exception?.let { + throw it } - config.activate() } - .addOnCompleteListener(this) { task -> - if (task.isSuccessful) { - // Parameter values successfully activated - // ... - } else { - // Handle errors - } + config.activate() + } + .addOnCompleteListener(this) { task -> + if (task.isSuccessful) { + // Parameter values successfully activated + // ... + } else { + // Handle errors } + } // [END perf_activate_config] } @@ -123,8 +124,10 @@ class MainActivity : AppCompatActivity() { // [START perf_manual_network_trace] val url = URL("https://www.google.com") - val metric = Firebase.performance.newHttpMetric("https://www.google.com", - FirebasePerformance.HttpMethod.GET) + val metric = Firebase.performance.newHttpMetric( + "https://www.google.com", + FirebasePerformance.HttpMethod.GET, + ) metric.trace { val conn = url.openConnection() as HttpURLConnection conn.doOutput = true diff --git a/perf/build.gradle b/perf/build.gradle index 0145c30c5..87591c53d 100644 --- a/perf/build.gradle +++ b/perf/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/storage/app/src/main/java/com/google/firebase/referencecode/storage/FirebaseUIActivity.java b/storage/app/src/main/java/com/google/firebase/referencecode/storage/FirebaseUIActivity.java index 8f04950ac..a62bd292d 100644 --- a/storage/app/src/main/java/com/google/firebase/referencecode/storage/FirebaseUIActivity.java +++ b/storage/app/src/main/java/com/google/firebase/referencecode/storage/FirebaseUIActivity.java @@ -1,5 +1,6 @@ package com.google.firebase.referencecode.storage; +import android.content.Context; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.widget.ImageView; @@ -17,6 +18,7 @@ protected void onCreate(Bundle savedInstanceState) { } public void loadWithGlide() { + Context context = this; // [START storage_load_with_glide] // Reference to an image file in Cloud Storage StorageReference storageReference = FirebaseStorage.getInstance().getReference(); @@ -26,7 +28,7 @@ public void loadWithGlide() { // Download directly from StorageReference using Glide // (See MyAppGlideModule for Loader registration) - Glide.with(this /* context */) + Glide.with(context) .load(storageReference) .into(imageView); // [END storage_load_with_glide] diff --git a/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/EmulatorSuite.kt b/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/EmulatorSuite.kt index 1d3ca85d1..5ee763c1c 100644 --- a/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/EmulatorSuite.kt +++ b/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/EmulatorSuite.kt @@ -1,8 +1,7 @@ package com.google.firebase.referencecode.storage.kotlin -import com.google.firebase.storage.FirebaseStorage -import com.google.firebase.storage.ktx.storage import com.google.firebase.ktx.Firebase +import com.google.firebase.storage.ktx.storage class EmulatorSuite { @@ -14,5 +13,4 @@ class EmulatorSuite { storage.useEmulator("10.0.2.2", 9199) // [END storage_emulator_connect] } - } diff --git a/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/FirebaseUIActivity.kt b/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/FirebaseUIActivity.kt index 884dc0834..3542b90bb 100644 --- a/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/FirebaseUIActivity.kt +++ b/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/FirebaseUIActivity.kt @@ -16,6 +16,7 @@ abstract class FirebaseUIActivity : AppCompatActivity() { } fun loadWithGlide() { + val context = this // [START storage_load_with_glide] // Reference to an image file in Cloud Storage val storageReference = Firebase.storage.reference @@ -25,9 +26,9 @@ abstract class FirebaseUIActivity : AppCompatActivity() { // Download directly from StorageReference using Glide // (See MyAppGlideModule for Loader registration) - Glide.with(this /* context */) - .load(storageReference) - .into(imageView) + Glide.with(context) + .load(storageReference) + .into(imageView) // [END storage_load_with_glide] } } diff --git a/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/StorageActivity.kt b/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/StorageActivity.kt index 3b0bd874b..ab48031b5 100644 --- a/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/StorageActivity.kt +++ b/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/StorageActivity.kt @@ -210,7 +210,7 @@ abstract class StorageActivity : AppCompatActivity() { // [START monitor_upload_progress] // Observe state change events such as progress, pause, and resume - // You'll need to import com.google.firebase.storage.ktx.component1 and + // You'll need to import com.google.firebase.storage.ktx.component1 and // com.google.firebase.storage.ktx.component2 uploadTask.addOnProgressListener { (bytesTransferred, totalByteCount) -> val progress = (100.0 * bytesTransferred) / totalByteCount @@ -233,7 +233,7 @@ abstract class StorageActivity : AppCompatActivity() { uploadTask = storageRef.child("images/${file.lastPathSegment}").putFile(file, metadata) // Listen for state changes, errors, and completion of the upload. - // You'll need to import com.google.firebase.storage.ktx.component1 and + // You'll need to import com.google.firebase.storage.ktx.component1 and // com.google.firebase.storage.ktx.component2 uploadTask.addOnProgressListener { (bytesTransferred, totalByteCount) -> val progress = (100.0 * bytesTransferred) / totalByteCount @@ -286,7 +286,8 @@ abstract class StorageActivity : AppCompatActivity() { // Create a reference from an HTTPS URL // Note that in the URL, characters are URL escaped! val httpsReference = storage.getReferenceFromUrl( - "https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg") + "https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg", + ) // [END download_create_reference] // [START download_to_memory] @@ -435,28 +436,27 @@ abstract class StorageActivity : AppCompatActivity() { // [START storage_list_all] val storage = Firebase.storage val listRef = storage.reference.child("files/uid") - - // You'll need to import com.google.firebase.storage.ktx.component1 and + + // You'll need to import com.google.firebase.storage.ktx.component1 and // com.google.firebase.storage.ktx.component2 listRef.listAll() - .addOnSuccessListener { (items, prefixes) -> - prefixes.forEach { prefix -> - // All the prefixes under listRef. - // You may call listAll() recursively on them. - } - - items.forEach { item -> - // All the items under listRef. - } + .addOnSuccessListener { (items, prefixes) -> + prefixes.forEach { prefix -> + // All the prefixes under listRef. + // You may call listAll() recursively on them. } - .addOnFailureListener { - // Uh-oh, an error occurred! + + items.forEach { item -> + // All the items under listRef. } + } + .addOnFailureListener { + // Uh-oh, an error occurred! + } // [END storage_list_all] } private fun processResults(items: List, prefixes: List) { - } // [START storage_list_paginated] @@ -471,20 +471,20 @@ abstract class StorageActivity : AppCompatActivity() { listRef.list(100) } - // You'll need to import com.google.firebase.storage.ktx.component1 and + // You'll need to import com.google.firebase.storage.ktx.component1 and // com.google.firebase.storage.ktx.component2 listPageTask - .addOnSuccessListener { (items, prefixes, pageToken) -> - // Process page of results - processResults(items, prefixes) - - // Recurse onto next page - pageToken?.let { - listAllPaginated(it) - } - }.addOnFailureListener { - // Uh-oh, an error occurred. + .addOnSuccessListener { (items, prefixes, pageToken) -> + // Process page of results + processResults(items, prefixes) + + // Recurse onto next page + pageToken?.let { + listAllPaginated(it) } + }.addOnFailureListener { + // Uh-oh, an error occurred. + } } // [END storage_list_paginated] diff --git a/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/UploadActivity.kt b/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/UploadActivity.kt index 7239386c1..f8ba725e9 100644 --- a/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/UploadActivity.kt +++ b/storage/app/src/main/java/com/google/firebase/referencecode/storage/kotlin/UploadActivity.kt @@ -74,8 +74,11 @@ abstract class UploadActivity : AppCompatActivity() { // [START restore_after_restart] // resume the upload task from where it left off when the process died. // to do this, pass the sessionUri as the last parameter - uploadTask = storageRef.putFile(localFile, - storageMetadata { }, sessionUri) + uploadTask = storageRef.putFile( + localFile, + storageMetadata { }, + sessionUri, + ) // [END restore_after_restart] } } diff --git a/storage/build.gradle b/storage/build.gradle index 302b37ca8..079fc78ec 100644 --- a/storage/build.gradle +++ b/storage/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/tasks/app/src/main/java/com/google/firebase/quickstart/tasks/kotlin/MainActivity.kt b/tasks/app/src/main/java/com/google/firebase/quickstart/tasks/kotlin/MainActivity.kt index 32c5dc3ba..c5df030b7 100644 --- a/tasks/app/src/main/java/com/google/firebase/quickstart/tasks/kotlin/MainActivity.kt +++ b/tasks/app/src/main/java/com/google/firebase/quickstart/tasks/kotlin/MainActivity.kt @@ -55,7 +55,9 @@ abstract class MainActivity : AppCompatActivity() { // [START listener_try_catch] val signInTask = Firebase.auth.signInWithEmailAndPassword( - "email@example.com", "mypassword1234") + "email@example.com", + "mypassword1234", + ) signInTask.addOnCompleteListener { task -> try { // Specific error information can be obtained by passing the expected @@ -76,8 +78,13 @@ abstract class MainActivity : AppCompatActivity() { // Create a new ThreadPoolExecutor with 2 threads for each processor on the // device and a 60 second keep-alive time. val numCores = Runtime.getRuntime().availableProcessors() - val executor = ThreadPoolExecutor(numCores * 2, numCores *2, - 60L, TimeUnit.SECONDS, LinkedBlockingQueue()) + val executor = ThreadPoolExecutor( + numCores * 2, + numCores * 2, + 60L, + TimeUnit.SECONDS, + LinkedBlockingQueue(), + ) // [END create_handler_and_executor] // [START tasks_run_task_executor] diff --git a/tasks/build.gradle b/tasks/build.gradle index 302b37ca8..079fc78ec 100644 --- a/tasks/build.gradle +++ b/tasks/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } } diff --git a/test-lab/app/src/main/java/com/google/firebase/example/testlab/kotlin/MainActivity.kt b/test-lab/app/src/main/java/com/google/firebase/example/testlab/kotlin/MainActivity.kt index 0537d2b53..64be498f2 100644 --- a/test-lab/app/src/main/java/com/google/firebase/example/testlab/kotlin/MainActivity.kt +++ b/test-lab/app/src/main/java/com/google/firebase/example/testlab/kotlin/MainActivity.kt @@ -1,8 +1,8 @@ package com.google.firebase.example.testlab.kotlin import android.provider.Settings -import androidx.appcompat.app.AppCompatActivity import android.util.Log +import androidx.appcompat.app.AppCompatActivity import com.google.android.libraries.cloudtesting.screenshots.ScreenShotter import java.io.FileNotFoundException @@ -60,9 +60,9 @@ class MainActivity : AppCompatActivity() { Log.i(TAG, "Log file ${it.encodedPath}") fd = try { contentResolver - .openAssetFileDescriptor(logFile, "w")!! - .parcelFileDescriptor - .fd + .openAssetFileDescriptor(logFile, "w")!! + .parcelFileDescriptor + .fd } catch (e: FileNotFoundException) { e.printStackTrace() -1 @@ -85,8 +85,9 @@ class MainActivity : AppCompatActivity() { } private fun takeScreenshot() { + val activity = this // [START ftl_take_screenshot] - ScreenShotter.takeScreenshot("main_screen_2", this /* activity */) + ScreenShotter.takeScreenshot("main_screen_2", activity) // [END ftl_take_screenshot] } } diff --git a/test-lab/build.gradle b/test-lab/build.gradle index 0145c30c5..87591c53d 100644 --- a/test-lab/build.gradle +++ b/test-lab/build.gradle @@ -8,7 +8,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.0.0' classpath 'com.google.gms:google-services:4.3.15' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.20" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21" } }