How to implement App Check in Flutter app - firebase

I'm trying to implement App Check in my Flutter app for Android and have followed the flutterfire documentation. I have already complete the installation part outlined here: https://firebase.flutter.dev/docs/app-check/overview
Now I am following this documentation for usage: https://firebase.flutter.dev/docs/app-check/usage
So I have added the await FirebaseAppCheck.instance.activate(webRecaptchaSiteKey: 'recaptcha-v3-site-key'); to my Main method, right after the call to initialize firebase.
Now I need to enable debugging with the App Check and the documentation says I should add this dependency to my app/build.gradle file: implementation 'com.google.firebase:firebase-appcheck-debug:16.0.0-beta01' and add the following code snippet to my MainActivity.java onCreate method:
import com.google.firebase.appcheck.FirebaseAppCheck;
FirebaseApp.initializeApp(/*context=*/ this);
FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.getInstance();
firebaseAppCheck.installAppCheckProviderFactory(DebugAppCheckProviderFactory.getInstance());
Which I have tried to do by creating the MainActivity.java with the following command in my project root folder: flutter create -a java .
So my MainActivity.java looks like this:
import io.flutter.embedding.android.FlutterActivity;
import com.google.firebase.appcheck.FirebaseAppCheck;
public class MainActivity extends FlutterActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(/*context=*/ this);
FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.getInstance();
firebaseAppCheck.installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance());
}
}
When trying to run the app in debug mode I get the this error: Execution failed for task ':app:compileDebugJavaWithJavac'.
What am I missing? Have seen other posts with the same problem but no solution.

This should be your main.dart
import 'package:firebase_app_check/firebase_app_check.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await FirebaseAppCheck.instance.activate();
}
Note: await FirebaseAppCheck.instance.activate(); does not have webRecaptchaSiteKey: 'recaptcha-v3-site-key' for Android/iOS App
This should be your MainActivity.kt
package com.example.app // your package
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import com.google.firebase.FirebaseApp
import com.google.firebase.appcheck.FirebaseAppCheck
import com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory
class MainActivity: FlutterActivity() {
private val CHANNEL = "samples.flutter.dev/example"
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
FirebaseApp.initializeApp(/*context=*/this)
val firebaseAppCheck = FirebaseAppCheck.getInstance()
firebaseAppCheck.installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance()
)
}
}
}

Related

Testing usage of Firebase create user functions with Coroutines and calling await() leads to "This job has not completed yet"

I have a simplified test case where I'm calling createUserWithEmailAndPassword(...).await() from FirebaseAuth that leads to the exception
java.lang.IllegalStateException: This job has not completed yet
I'm using the InstantTaskExecutorRule but this doesn't help.
Here is my simplified test class:
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Rule
import org.junit.Test
class FirebaseCoroutineTest {
#get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
val auth = Firebase.auth.apply {
this.useEmulator("10.0.2.2", 9099)
}
#Test
fun testCreateUser() = runBlockingTest {
auth.createUserWithEmailAndPassword("test#user.null", "testpwd").await()
}
}
What's the correct way to do this test.
using runBlocking instead of runBlockingTest solves the issue.

error: cannot find symbol FirebaseAdMobPlugin.registerNativeAdFactory(flutterEngine, "moviesTorrentAdFactory", NativeAdFactoryExample());

I'm using flutter , and I tried to use Native Ads following this doc
all ads are working fine but Native ad doesn't work and it fails building the app showing this error
error: cannot find symbol FirebaseAdMobPlugin.registerNativeAdFactory(flutterEngine, "moviesTorrentAdFactory", NativeAdFactoryExample());
this is MyActivity.java file :
package tech.devm.movies_torrent;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.firebaseadmob.FirebaseAdMobPlugin;
import com.google.android.gms.ads.formats.UnifiedNativeAd;
import com.google.android.gms.ads.formats.UnifiedNativeAdView;
import io.flutter.plugins.firebaseadmob.FirebaseAdMobPlugin.NativeAdFactory;
import java.util.Map;
public class MainActivity extends FlutterActivity {
#Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {
flutterEngine.getPlugins().add(new FirebaseAdMobPlugin());
FirebaseAdMobPlugin.registerNativeAdFactory(flutterEngine, "moviesTorrentAdFactory", NativeAdFactoryExample());
}
#Override
public void cleanUpFlutterEngine(FlutterEngine flutterEngine) {
FirebaseAdMobPlugin.unregisterNativeAdFactory(flutterEngine, "moviesTorrentAdFactory");
}
}
class NativeAdFactoryExample implements NativeAdFactory {
#Override
public UnifiedNativeAdView createNativeAd(
UnifiedNativeAd nativeAd, Map<String, Object> customOptions) {
// Create UnifiedNativeAdView
}
}
is there should be any changes to Manifest.xml file ? or am I missing something ?
I've cleared the build using (flutter clean ) many times but nothing works
any help would be much appreciated
I was also having the exact same issue. This is how I fix it!
Seems that this error is related with the NativeAdFactory file (eg: ListTileNativeAdFactory.java) and the layout at app/src/main/res/layout/list_title_native_ad.xml
If you go to the Google Codelabs example at https://github.com/googlecodelabs/admob-inline-ads-in-flutter/tree/main/complete and copy those files exactly like the example you will solve that problem.

Why my kotlin code for Firebase authentication not working?

I am enrolled in online CBT and learning Kotlin for android programming. The video tutes were made in 2017 and I got codes of the apps that were made in the to the tutorial series. I have followed every step till I connect my app with Firebase and even entered sample user data in Authentication and set Usage Rules to public, but to my surprise same Kotlin code which was shown to be working flawlessly in video tutorials does not work for me.
Then I tried sample LoginActivity.kt and RegisterActivity.kt codes from github, even those codes does not work. Please look at my codes and help me sort out this issue.
When I click on loginBtn the app crashes and not data is sent to Firebase. Logcat shows following error:
java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.paramlowe.mypg2. Make sure to call
FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(SourceFile:218)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source:1)
at com.punjabweb.myapp.LoginActivity.loginUser(LoginActivity.kt:50)
at
com.punjabweb.myapp.LoginActivity.access$loginUser(LoginActivity.kt:25)
at
com.punjabweb.myapp.LoginActivity$onCreate$2.onClick(LoginActivity.kt:43)
and my kotlin code for LoginActivity.kt is here below:
package com.punjabweb.myapp2
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : AppCompatActivity() {
//Firebase references
private var mAuth: FirebaseAuth? = null
// FirebaseApp.initializeApp(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val loginBtn = findViewById<View>(R.id.btnLogin) as Button
loginBtn.setOnClickListener {
loginUser()
}
}
private fun loginUser() {
mAuth = FirebaseAuth.getInstance()
val email = etEmail?.text.toString()
val password = etPassword?.text.toString()
if (TextUtils.isEmpty(email) && TextUtils.isEmpty(password)) {
Toast.makeText(this, "Enter all details", Toast.LENGTH_SHORT).show()
} else {
mAuth!!.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with signed-in user's information
var firebasUser = FirebaseAuth.getInstance().currentUser!!
// updateUI()
} else {
// If sign in fails, display a message to the user.
Toast.makeText(
this#LoginActivity, "Authentication failed.",
Toast.LENGTH_SHORT
).show()
}
}
}
fun updateUI() {
val intent = Intent(this#LoginActivity, MainActivity::class.java)
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)
}
}
}
You need to enable the firebase email authentication in the console. Seems like your code is ok in the first look.
This could potentially be cause because you don't have the google-services plugin at the end of app gradle:
dependencies {
....
}
apply plugin: 'com.google.gms.google-services'

Cannot resolve SetImageResource

I have this code
package com.kmsmartapps.test5;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
public void clickIM(View view) {
ImageView image = (ImageView) findViewById(R.id.imview);
image.SetImageResource(R.drawable.logo);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Android studio shows error :
Error:(11, 14) error: cannot find symbol method SetImageResource(int)
I want to change the source image using a button. With android studio 2.3 it worked fine but now using android studio 3.0 it doesn't work.
I tried solutions proposed in this forum but still showing error.
Can you tell how to fix this ?
Thanks
It was an error writing SetImageResource. I must write it with small s like this setImageResource. When changing to small the problem was resolved.

react-native-firebase install - package io.invertase.firebase does not exist?

I am getting the following issues when running "react-native run-android" in my project. I've gone through the react-native-firebase per normal but in this case I can't quite see what I might have done wrong?
:app:incrementalDebugJavaCompilationSafeguard UP-TO-DATE
:app:compileDebugJavaWithJavac
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:11: error: package io.invertase.firebase does not exist
import io.invertase.firebase.RNFirebasePackage;
^
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:12: error: package io.invertase.firebase.auth does not exist
import io.invertase.firebase.auth.RNFirebaseAuthPackage;
^
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:13: error: package io.invertase.firebase.firestore does not exist
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage;
^
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:30: error: cannot find symbol
new RNFirebasePackage(),
^
symbol: class RNFirebasePackage
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:31: error: cannot find symbol
new RNFirebaseAuthPackage(),
^
symbol: class RNFirebaseAuthPackage
/source/myapp/android/app/src/main/java/com/gctodo/MainApplication.java:32: error: cannot find symbol
new RNFirebaseFirestorePackage()
^
symbol: class RNFirebaseFirestorePackage
6 errors
:app:compileDebugJavaWithJavac FAILED
MainApplication.java is for exampe:
package com.gctodo;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.auth.RNFirebaseAuthPackage;
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNFirebasePackage(),
new RNFirebaseAuthPackage(),
new RNFirebaseFirestorePackage()
);
}
#Override
protected String getJSMainModuleName() {
return "index";
}
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
It appears that RNFirebasePackage is missing and cannot be found during compile step.
Try running
react-native link
after install, followed by clean and then run the build.
running react-native link did not work for me. I had to delete the android and ios project folders and then ran
react-native eject
which recreated both the ios and android folders. I was able to run the builds now.
For anyone else that gets stuck here, I needed to do npm i #react-native-firebase/messaging

Resources