Good day all,
I am implementing AWS Amplify DataStore for android following the docs, and basically i get this error when i try to initialize the data store plugin on amplify according to this part of the doc:
Cannot resolve symbol 'AmplifyModelProvider'
You can find code from my gradle files and my application class below.
I am not an android expert, but i believe this is because of a missing dependency or i am doing something wrong during initialization or assignation of the ModelProvider. But i cant find any information on internet about this issue or any possible solution.
Thanks in advance for your help.
Steps to reproduce:
Create new android project
Install Amplify CLI, using npm, npm install -g #aws-amplify/cli
Configure amplify, amplify configure
On new android project root folder, run amplify init, amplify init
On new android project root folder, run amplify add auth, amplify add auth, adding authentication
Create android application class
Add android application class to AndroidManifest.xml
Try to add data store plugin to amplify on onCreate method of the application class
I already try the following solutions:
Clean project
Rebuild project
Run Make Project
Close and open again Android Studio
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bakeano.htejobs">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MyApplication.java
package com.bakeano.htejobs;
import android.app.Application;
import android.util.Log;
import com.amazonaws.mobile.client.AWSMobileClient;
import com.amazonaws.mobile.client.Callback;
import com.amazonaws.mobile.client.UserStateDetails;
import com.amplifyframework.api.aws.AWSApiPlugin;
import com.amplifyframework.core.Amplify;
import com.amplifyframework.core.model.ModelProvider;
import com.amplifyframework.datastore.AWSDataStorePlugin;
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// AWSMobileClient initialization
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
#Override
public void onResult(UserStateDetails result) {
try {
ModelProvider modelProvider = AmplifyModelProvider.getInstance(); // Error on this line !!!
Amplify.addPlugin(AWSDataStorePlugin.forModels(modelProvider));
Amplify.addPlugin(new AWSApiPlugin());
Amplify.configure(getApplicationContext());
} catch (Exception e) {
Log.e("bakeanoMessage", "Amplify adding plugins Exception: " + e.getMessage(), e);
}
}
#Override
public void onError(Exception e) {
Log.e("bakeanoMessage", "AWSMobileClient init Exception: " + e.getMessage(), e);
}
});
}
}
Module Gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.bakeano.htejobs"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
// androidx constraint layout
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta4'
// aws amplify framework core
implementation 'com.amplifyframework:core:0.10.0'
// AWSMobileClient
implementation 'com.amazonaws:aws-android-sdk-mobile-client:2.16.11'
// aws amplify for the drop-in ui
implementation 'com.amazonaws:aws-android-sdk-auth-userpools:2.16.11'
implementation 'com.amazonaws:aws-android-sdk-auth-ui:2.16.11'
// aws amplify api
implementation 'com.amplifyframework:aws-api:0.10.0'
// aws amplify data store
implementation 'com.amplifyframework:aws-datastore:0.10.0'
}
Project Gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.2'
// amplify tools gradle plugin
classpath 'com.amplifyframework:amplify-tools-gradle-plugin:0.2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
// applying the amplify tools plugin
apply plugin: 'com.amplifyframework.amplifytools'
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Solution provided by Jameson Williams:
at projects github issue platform - issue #370
AmplifyModelProvider is an autogenerated file that is created by amplify codegen
amplify codegen models
after manual generation you need to import it:
import com.amplifyframework.datastore.generated.model.AmplifyModelProvider;
Thanks !!
Related
This question already has answers here:
Failed to resolve com.google.android.gms play-services-auth:11.4.0
(13 answers)
Failed to resolve: com.android.support:cardview-v7:26.0.0 android
(26 answers)
Closed 5 years ago.
I'm trying to follow the tutorial for the Google Payment API found here:
https://developers.google.com/payments/setup
I'm getting the following errors when I sync the gradle
Mainly - I get the error:
Failed to resolve: com.google.android.gms:play-services-wallet:11.4.0
There is a link under the error to "Install Repository and sync project" but when I click that, nothing happens.
Is there a way to manually install the necessary repository? Is there something else that I'm missing? What repository do I even need to install? I've tried to update everything.
Gradle:
{
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
applicationId "com.google.android.gms.samples.wallet"
minSdkVersion 26
targetSdkVersion 26
versionCode 1
versionName "1.0"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.google.android.gms:play-services-wallet:11.4.0'
compile 'com.google.android.gms:play-services-tasks:11.4.0'
compile 'com.google.android.gms:play-services-base:11.4.0'
compile 'com.google.android.gms:play-services-basement:11.4.0'
}
Top Level Gradle
buildscript {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name="MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Enables the Google Payment API -->
<meta-data
android:name="com.google.android.gms.wallet.api.enabled"
android:value="true" />
</application>
I've been trying to get this to run for about a week, and can't get the the gradle to sync whenever I include google wallet. I've followed the tutorial as closely as I can. I've tried it with their sample app from github, from my own app, from a couple apps from scratch. I have no idea how to get this repository to work.
Thanks.
John
You should add the google maven to allprojects not to buildscript. So, change it to something like this:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
I was having the same issue this morning as well... But the Fix is Instead of using "11.4.0" you should be using "11.0.4". Maybe an error on their website because when you put "11.4.0" Android Studio is giving you that error and it tells you to update to the latest version which is "11.0.4".
To sum up, use this one and it should work
compile 'com.google.android.gms:play-services-wallet:11.0.4'
I am facing this issue and seen some answers on this site but did not get any proper solution.
I have used previous version of Firebase which works fine but when I try to upgrade using Upgradation and update Firebase class to DatabaseReference it shows error and not working.
I am adding my manifest file entire code so please help me to resolve this issue.
Here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="firebasechat.com.firebasechat">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:name=".Activity.SimpleBlog"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Activity.RegisterActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
my Module app is given below.
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
applicationId "firebasechat.com.firebasechat"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.volley:volley:1.0.0'
compile "com.google.firebase:firebase-database:11.0.0"
compile 'com.google.android.gms:play-services:11.0.0'
compile 'com.android.support:recyclerview-v7:25.0.0'
testCompile 'junit:junit:4.12'
testCompile 'junit:junit:4.12'
}
and Project gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'com.google.gms:google-services:4.2.0'// Updated version of google service
}
}
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com" // Google's Maven repository
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Below is my Activity.
public class RegisterActivity extends AppCompatActivity {
EditText username, password;
Button registerButton;
String user, pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
registerButton = (Button)findViewById(R.id.registerButton);
FirebaseApp.initializeApp(this);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user = username.getText().toString();
pass = password.getText().toString();
final ProgressDialog pd = new ProgressDialog(RegisterActivity.this);
pd.setMessage("Loading...");
pd.show();
String url = "https://pure-coda-174710.firebaseio.com/users.json";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
// Firebase reference = new Firebase("https://pure-coda-174710.firebaseio.com/users");
DatabaseReference reference = FirebaseDatabase.getInstance()
.getReferenceFromUrl("https://pure-coda-174710.firebaseio.com/users");
if(s.equals("null")) {
reference.child(user).child("password").setValue(pass);
Toast.makeText(RegisterActivity.this, "registration successful", Toast.LENGTH_LONG).show();
}
else {
try {
JSONObject obj = new JSONObject(s);
if (!obj.has(user)) {
reference.child(user).child("password").setValue(pass);
Toast.makeText(RegisterActivity.this, "registration successful", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(RegisterActivity.this, "username already exists", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
pd.dismiss();
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError );
pd.dismiss();
}
});
RequestQueue rQueue = Volley.newRequestQueue(RegisterActivity.this);
rQueue.add(request);
}
});
}
}
In your SimpleBlog application class, initialize FirebaseApp in onCreate() method and remove it from RegisterActivity in order to have Firebase initialize into entire application, not just one Activity.
#Override
public void onCreate() {
super.onCreate();
FirebaseApp.initializeApp(this);
}
Also add apply plugin: 'com.google.gms.google-services' at the end of app gradle:
dependencies {
....
}
apply plugin: 'com.google.gms.google-services'
Plugin is required to process your json config from firebase and to avoid dependency collisions. You can read here for more details.
Spent literally a whole day. Finally, this was the solution.
Freaking 0 instead of 1 and you will not have to use the initialize firebaseapp or anything like that.
In Project gradle, use Google services: 4.0.0 and not 4.1.0.
Plus, apply plugin statement at the end is also not necessary in my experience.
(Hoping you have added firebase database from the tools => firebase assistant. Step 1 and step 2 are right and green. )
According to FirebaseApp documentation, you do not need to invoke this initialization, except that your app requires access to another Firebase project.
I invoked this initialization and sometime, user gets crash time to time when user opens my app, so I remove this line of code then everything works well. Be careful to invoke this initialization.
The capture of FirebaseApp documentation:
Update: below Exception will occur if you try to add this line [Some ads network requires this line, they also add some process in their AndroidManifest]
Failed to gain exclusive lock to the Firestore client's offline persistence. This generally means you are using Firestore from multiple processes in your app. Keep in mind that multi-process Android apps execute the code in your Application class in all processes, so you may need to avoid initializing Firestore in your Application class. If you are intentionally using Firestore from multiple processes, you can only enable offline persistence (i.e. call setPersistenceEnabled(true)) in one of them.
To fix it:
1) add below method in your Application class:
private boolean isMainProcess(Context context) {
if (null == context) {
return true;
}
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int pid = android.os.Process.myPid();
for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
if (APPLICATION_ID.equals(processInfo.processName) && pid == processInfo.pid) {
return true;
}
}
return false;
}
2) Wrap onCreate of your Application
#Override
public void onCreate() {
super.onCreate();
if (!isMainProcess(this)) {
FirebaseApp.initializeApp(this);
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(false)
.build();
FirebaseFirestore.getInstance().setFirestoreSettings(settings);
// other things
return;
}
// other things
}
UPDATE: Sometime, my app throws below exception
Unable to create application My Application Class : java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process MY_APPLICATION_ID. Make sure to call FirebaseApp.initializeApp(Context) first.
To Fix It: let update onCreate method:
#Override
public void onCreate() {
super.onCreate();
FirebaseApp.initializeApp(this);
boolean isMain = isMainProcess(this);
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder().setPersistenceEnabled(isMain).build();
FirebaseFirestore.getInstance().setFirestoreSettings(settings);
if (!isMain) {
// other things
return;
}
// other things
}
Got same problem and solved this way:
in activity:
#Override
public void onCreate() {
super.onCreate();
FirebaseApp.initializeApp(this);
}
in app's gradle (at the end of file):
dependencies {
....
}
apply plugin: 'com.google.gms.google-services'
is project's gradle:
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:3.0.0'
}
I had this same issue some time ago.
You're trying to get an instance of Firebase without initialize it.
Please add this line of code before you try to get an instance of
Firebase:
Just import latest version firebase and google play services.
Recent update version (example):
add to these lines build.gradle
dependencies {
implementation 'com.google.firebase:firebase-messaging:17.3.4'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
}
apply plugin: 'com.google.gms.google-services'
dependencies {
classpath 'com.android.tools.build:gradle:3.3.1'
classpath 'com.google.gms:google-services:4.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
thats all. Enjoy your coding.
First thing first: Project config JSON's may go wrong/obsolete mostly on upgrade of Firebase.
Go to Tools->Firebase->Cloud Messaging->Set up firebase cloud messaging.
Even if you have done that in the past, it's worth the double check here as things get updated from time to time. I sync-ed my project and it solved the issue.
As for calling FirebaseApp.initializeApp, it is not necessary, at least not for FCM. See the FCM documentations.
Furthermore, if it return null it means that it fails, so calling it before calling getInstance won't do.
Note that this is the getInstance of FirebaseInstanceId:
public static FirebaseInstanceId getInstance() {
return getInstance(FirebaseApp.getInstance());
}
Where on the other hand:
#Nullable
public static FirebaseApp initializeApp(Context var0) {
Object var1 = sLock;
synchronized(sLock) {
if (zzf.containsKey("[DEFAULT]")) {
return getInstance();
} else {
FirebaseOptions var2;
return (var2 = FirebaseOptions.fromResource(var0)) == null ? null : initializeApp(var0, var2);
}
}
}
It means that it's if initializeApp returns null, you probably have issues with the configurations. At least - worth checking. To know where you are at, put a breakpoint at some point where Context is visible, and try to evaluate FirebaseApp.initialize(context) to make sure it does not return null.
Please downgrade google service plugin from version 4.1.0 to 4.0.1 in project's build.gradle
classpath 'com.google.gms:google-services:4.0.1'
And add this code to onCreate()
FirebaseApp.initializeApp(this);
it worked for me.
I had the same problem too and i noticed that this problem only occured to me when i added Firebase Storage dependency.
So as i am using API 28, I made sure that all firebase dependencies have same import version i.e 16.0.5as of the storage dependency.
implementation 'com.google.firebase:firebase-core:16.0.5'
implementation 'com.google.firebase:firebase-auth:16.0.5'
implementation 'com.google.firebase:firebase-database:16.0.5'
implementation 'com.google.firebase:firebase-storage:16.0.5'
I updated my gradle version to
classpath 'com.android.tools.build:gradle:3.3.0'
classpath 'com.google.gms:google-services:4.2.0'
And i added the line below the app module
apply plugin: 'com.google.gms.google-services'
then it worked for me.
To prevent this error, one need to follow all the steps involved in setting up Firebase for android https://firebase.google.com/docs/android/setup
I got the same error as I forgot to follow two steps and fixed it by
1) adding classpath 'com.google.gms:google-services:4.2.0' to project level gradle build file.
2) adding apply plugin: 'com.google.gms.google-services' to module level gradle build file.
update the gradle main classpath 'com.google.gms:google-services:4.2.0'
No need to add anything in Application class or call initializeApp() for firebase. After adding firebase capabilities to your app through Tools -> Firebase - > (Any functionality) -> Make sure step 1 and 2 is green and checked.
Go to project gradle file and use
classpath 'com.google.gms:google-services:4.2.0'
that's it.
I didn't use FirebaseApp.initializeApp(Context) on my project.
It works for me. You should check your gradle files and be sure you implemented this lines:
add apply plugin: 'com.google.gms.google-services' into your gradle(app)
or
add this classpath 'com.google.gms:google-services:4.2.0' into your gradle(project).
I had the same problem , i Modified my Project build.gradle to be as follows
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:3.2.0'
....
}
then i added the line below into the app module
apply plugin: 'com.google.gms.google-services'
and it was solved
You are experiencing this error because of google updata, All you need is do the following
Change the following dependency from
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'com.google.gms:google-services:4.1.0'
}
to
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'com.google.gms:google-services:4.0.0'
}
The difference is that google-services:4.1.0 should be changed to 4.0.0
Also you might be missing this plugin
apply plugin: 'com.google.gms.google-services'
implementation 'com.google.firebase:firebase-core:16.0.6
If error FirebaseApp.initializeApp(Context) add "mavenCentral" in your build.gradle
enter code here repositories {google() jcenter() mavenCentral() }
Try to downgrade or upgrade the Gradle version.
For example, your build.gradle have :
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
}
Change to
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
}
Try adding your app to firebase console and updating the new google-services.json file in your application. This worked for me, when I had tried to implement the app with the database and json file of another project.
After migration you have to update the dependencies to the new SDK, check this: https://stackoverflow.com/a/61681739/5279996
You are using very old method of firebase now you dont need to use
***FirebaseApp.initializeApp(context)***
remove this. then:
Just add Your App with package name to your firebase project download the google Json file
from this link here
add your package name and then copy the downloaded google json file in your “app” now Add
the instructed libraries into both app level and project level gradle. now just sync the
project and you are ready to use firebase.
When this error occurs, it's because you are not using the latest version of firebase dependencies.
Update all dependencies to the latest ones and you are good to go!
put these two lines in build.gradle ( app level )
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
( this picture taken from Firebase > Settings > Android App > Method of setting SDK
if it is correct , it will yeild error cannot find file 'google-services.json'
then you copy your google-service.json file that generated from
Firebase > Setting > Android App > Click "google-services.json" to genetate the file.
You do not have to worry about the path that you will save this file.
The error will show where do you need to save this file.
For example I save in app/ ( next to build.gradle (app level ))
Using Kotlin,
"Make sure to call FirebaseApp.initializeApp(Context) first in
Android"
this is an example for a correct Firebase Analytics initialization:
// declare_analytics
private lateinit var firebaseAnalytics: FirebaseAnalytics
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Obtain the FirebaseAnalytics instance.
firebaseAnalytics = Firebase.analytics
val parameters = Bundle().apply {
this.putString("level_name", "Jorgesys B. " + System.currentTimeMillis())
this.putInt("level_difficulty", 10)
}
firebaseAnalytics.setDefaultEventParameters(parameters)
}
I want to Set up a firebase Cloud Messaging Client App on Android studio,
I am using latest version of Android studio(2.3.3) and my android SDK is fully updated.
Here is my project gradle file:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.google.gms:google-services:3.1.0'
classpath 'com.android.tools.build:gradle:2.3.3'
}
}
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
and this is my app build gradle file :
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "ir.digiwindow.driver.gps_status"
minSdkVersion 14
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
testCompile 'junit:junit:4.12'
compile 'com.google.firebase:firebase-messaging:11.0.4'
}
apply plugin: 'com.google.gms.google-services'
and I always give this error :
Error:(30, 13) Failed to resolve: compile 'com.google.firebase:firebase-messaging:11.0.4'
The interesting point here is that when I change version from 11.0.4 to 10.0.1 no error occurs and gradle build successfully!
I read all related posts in stackoverflow and google developer site, but this error still exists!
Any ideas welcome...
Edit 1:
when I go to look for updates I don't see any option about updating google play service here in the image:
I have faced the same problem, I have resolved it by updating two things
Google play service
Google repository
Mr Jan, Please follow below link its clearly says that->
https://firebase.google.com/docs/android/setup#Prerequisites
Prerequisites-
A device running Android 4.0 (Ice Cream Sandwich) or newer, and Google Play services 11.6.0 or higher
The Google Play services SDK from the Google Repository, available in the Android SDK Manager
The latest version of Android Studio, version 1.5 or higher
So Upgrade your Google Play Services and Google Repository in SDK Manager
Open Android studio > Go to File > Settings > Appearance and Behavior > System Setting > Android SDK > SDK Tools > Update
1- Google Play Services and
2- Google Repository under Support Repository
As Dileep mentioned from the documentation, you need to have Google Play Services 11.0.4 or higher installed.
Just open the SDK Manager,
Then Android SDK (on the left hand menu)
Then to the SDK Tools Tab and update Google Play Services, which is currently in version 43 (2017-08-10).
That solved it for me.
Try to add Firebase features through firebase Assitance go to Tools then Firebase and then select which feature you want to add like Realtime Database.
It will automatically add the compile dependencies to your project. I did the same and solved my problem.
It should be this way:
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
classpath 'com.google.gms:google-services:3.1.1' // ADD this
}
app: (11.8.0)
implementation 'com.google.firebase:firebase-messaging:11.8.0' // ADD this
Un Tick Offline Gradle Build will solve this issue if any of the above solution not working
As of 1-10-2020, this is what worked for me.
Top level build.gradle file:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.1"
classpath 'com.google.gms:google-services:4.3.4'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
App level build.gradle file:
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
//Top code is same as= apply plugin: 'com.android.application'
android {
compileSdkVersion 30
buildToolsVersion "30.0.0"
defaultConfig {
applicationId "com.gc.pushnotificationssampleapp2"
minSdkVersion 24
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
//Start of unique libs for this project:
implementation 'com.google.firebase:firebase-messaging:20.0.1'
}
Make sure you have your app registered in Firebase. So you should have a google-services.json file in your project with your project's package name in it, something like this:
"client_info": {
"mobilesdk_app_id": "1:551460864994:android:c0310a960a3afb06df2fbb",
"android_client_info": {
"package_name": "com.gc.pushnotificationssampleapp2"
}
AndroidManifest.xml will need:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
. . .
<service
android:name=".FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Gradle version, firebase services version and google-play-services versions should be same when using. you may not use gradle 2.x with firebase core 16.x for example.
The solution is to update to the latest version of the classpath of com.google.gms:google-services
which is hinted by Android Studio in file build.gradle of the project
add in gradle
Dependencies{
// for the Firebase
implementation platform('com.google.firebase:firebase-bom:26.5.0')
implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-messaging:20.1.3'
implementation 'com.google.firebase:firebase-analytics:17.2.3'
}
apply plugin: 'com.google.gms.google-services'
and add in manifest
<application>
<service android:name=".util.FirebaseMessageReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
and FirebaseMessageReceiver.java
this is with custom layout
package com.---------.app.util;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.widget.RemoteViews;
import androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.pisel.app.MainActivity;
import com.pisel.app.R;
public class FirebaseMessageReceiver
extends FirebaseMessagingService {
// Override onMessageReceived() method to extract the
// title and
// body from the message passed in FCM
#Override
public void
onMessageReceived(RemoteMessage remoteMessage) {
// First case when notifications are received via
// data event
// Here, 'title' and 'message' are the assumed names
// of JSON
// attributes. Since here we do not have any data
// payload, This section is commented out. It is
// here only for reference purposes.
/*if(remoteMessage.getData().size()>0){
showNotification(remoteMessage.getData().get("title"),
remoteMessage.getData().get("message"));
}*/
// Second case when notification payload is
// received.
if (remoteMessage.getNotification() != null) {
// Since the notification is received directly from
// FCM, the title and the body can be fetched
// directly as below.
showNotification(
remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody());
}
}
// Method to get the custom Design for the display of
// notification.
private RemoteViews getCustomDesign(String title,
String message) {
RemoteViews remoteViews = new RemoteViews(
getApplicationContext().getPackageName(),
R.layout.notification);
remoteViews.setTextViewText(R.id.title, title);
remoteViews.setTextViewText(R.id.message, message);
remoteViews.setImageViewResource(R.id.icon,
R.drawable.flag_belarus);
return remoteViews;
}
// Method to display the notifications
public void showNotification(String title,
String message) {
// Pass the intent to switch to the MainActivity
Intent intent
= new Intent(this, MainActivity.class);
// Assign channel ID
String channel_id = "notification_channel";
// Here FLAG_ACTIVITY_CLEAR_TOP flag is set to clear
// the activities present in the activity stack,
// on the top of the Activity that is to be launched
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Pass the intent to PendingIntent to start the
// next Activity
PendingIntent pendingIntent
= PendingIntent.getActivity(
this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
// Create a Builder object using NotificationCompat
// class. This will allow control over all the flags
NotificationCompat.Builder builder
= new NotificationCompat
.Builder(getApplicationContext(),
channel_id)
.setSmallIcon(R.drawable.flag_india)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000, 1000,
1000, 1000})
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent);
// A customized design for the notification can be
// set only for Android versions 4.1 and above. Thus
// condition for the same is checked here.
if (Build.VERSION.SDK_INT
>= Build.VERSION_CODES.JELLY_BEAN) {
builder = builder.setContent(
getCustomDesign(title, message));
} // If Android Version is lower than Jelly Beans,
// customized layout cannot be used and thus the
// layout is set as follows
else {
builder = builder.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.flag_british_indian_ocean_territory);
}
// Create an object of NotificationManager class to
// notify the
// user of events that happen in the background.
NotificationManager notificationManager
= (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
// Check if the Android Version is greater than Oreo
if (Build.VERSION.SDK_INT
>= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel
= new NotificationChannel(
channel_id, "web_app",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(
notificationChannel);
}
notificationManager.notify(0, builder.build());
}
}
create a layout for notification design
<!-- Parent Layout of ImageView -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!--Image to be displayed beside the notification text-->
<ImageView
android:id="#+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="5dp"
android:src="#drawable/flag_benin" />
</LinearLayout>
<!-- Parent layout for holding the Title and the Body-->
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:padding="5dp">
<!-- TextView for Title -->
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:textColor="#000"
android:textStyle="bold" />
<!-- TextView for Body -->
<TextView
android:id="#+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Message"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
For those who use firebase bom
implementation platform('com.google.firebase:firebase-bom:29.0.1')
// Firebase Cloud Messaging (Java)
implementation 'com.google.firebase:firebase-messaging'
// Firebase Cloud Messaging (Kotlin)
implementation 'com.google.firebase:firebase-messaging-ktx'
// For an optimal experience using FCM, add the Firebase SDK
// for Google Analytics. This is recommended, but not required.
implementation 'com.google.firebase:firebase-analytics'
I had the same problem. Later discovered I copied the line exactly from firebase docs.
Classpath 'com.google.gms:google-services:3.1.1'
Notice the CAPITAL 'C'.
it should be
classpath 'com.google.gms:google-services:3.1.1'
with lower case 'c'.
Dumb mistake but easily unnoticeable.
I had the same problem and I just changed the version from 11.0.4 to 10.0.1 and the error went away. Just try it, it may be helpful.
I'm trying to integrate Firebase on Unity3d in order to receive push notifications.
I get the following error when the app launching:
I/dalvikvm( 7881): Could not find method android.content.Context.isDeviceProtectedStorage, referenced from method com.google.firebase.FirebaseApp.zza
I/FirebaseInitProvider( 7881): FirebaseApp initialization unsuccessful
The firebase-messaging sample work fine with my google-services.json. So I suppose that the console configuration is correct.
1. I created a library project on Android Studio.
I followed a web site to build a .jar from Android Studio and the official documentation to add firebase.
http://www.thegamecontriver.com/2015/04/android-plugin-unity-android-studio.html
project gradle file:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.1'
classpath 'com.google.gms:google-services:3.0.0'
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
app gradle file:
apply plugin: 'com.android.library'
android {
compileSdkVersion 24
buildToolsVersion "24.0.3"
sourceSets {
main {
java {
srcDir 'src/main/java'
}
}
}
defaultConfig {
minSdkVersion 15
targetSdkVersion 24
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
abortOnError false
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.google.firebase:firebase-core:9.6.1'
compile 'com.google.firebase:firebase-messaging:9.6.1'
compile files('libs/classes.jar')
}
task deleteOldJar(type: Delete) {
delete 'release/NotificationPlugin.jar'
}
task exportJar(type: Copy) {
from('build/intermediates/bundles/release/')
into('release/')
include('classes.jar')
rename('classes.jar', 'NotificationPlugin.jar')
}
exportJar.dependsOn(deleteOldJar, build)
apply plugin: 'com.google.gms.google-services'
At this point a .jar is successfully generated.
2. I created a JarResolver dependencies in Unity.
I use the PlayServicesResolver v1.1 found into other google unity package (Google analytics for exemple, other plugins upgrade it)
https://github.com/googleanalytics/google-analytics-plugin-for-unity
FirebaseDependencies.cs
using Google.JarResolver;
using UnityEditor;
[InitializeOnLoad]
public static class FirebaseDependencies
{
private static readonly string PluginName = "Firebase";
static FirebaseDependencies()
{
PlayServicesSupport svcSupport = PlayServicesSupport.CreateInstance(
PluginName,
EditorPrefs.GetString("AndroidSdkRoot"),
"ProjectSettings");
svcSupport.DependOn("com.google.firebase",
"firebase-core",
PluginVersion.PlayServicesVersionConstraint);
svcSupport.DependOn("com.google.firebase",
"firebase-messaging",
PluginVersion.PlayServicesVersionConstraint);
}
}
PluginVersion.cs
public class PluginVersion
{
public const string PlayServicesVersionConstraint = "9.6+";
}
After the ResolveClientJars command, all dependencies are copy into the Plugins/Android folder.
AndroidManifest.xml
firebase-analytics-9.6.1
firebase-analytics-impl-9.6.1
firebase-common-9.6.1
firebase-core-9.6.1
firebase-iid-9.6.1
firebase-messaging-9.6.1
google-services.json
play-services-basement-9.6.1
play-services-tasks-9.6.1
support-annotations-24.0.0.jar
support-v4-24.0.0
Everything seems to work perfectly at this point and there are no error during the build process.
What I'm doing wrong?
You could use Firebase Push Notifications without creation additional plugin. But the flow is a little bit tricky. Here are quick steps:
In the Unity Editor. In the Build Settings select Google Android
Project flag and Export your project. Make sure that your bundle id
correspond to the bundle id at the Firebase Console.
In the Android Studio. Import your Unity project. IMPORTANT: Don't
Open, Import!
Setup .gradle scripts and add google-services.json file as described here.
Build project from Android Studio.
Our Gradle build script fails when building Javadocs for Android Studio project for a library we develop, with errors like:
/MY_LOCAL_PATH/MyClass.java:5: error: package com.google.gson does not exist
import com.google.gson.Gson;
Details:
We are building an Android library with Gradle, and want to build the Javadocs for it.
The Android Studio project is configured to require a Maven dependency for GSON, although I'm guessing it would happen with every dependency whose lib file is not provided explicitly.
One of our classes, of course, imports com.google.gson.
Here is our Gradle script:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
apply plugin: 'com.android.library'
android {
compileSdkVersion 19
buildToolsVersion '21.1.2'
defaultConfig {
minSdkVersion 19
targetSdkVersion 19
versionCode 8000
versionName "0.8.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.code.gson:gson:2.2.4'
}
And the task that's expected to build the docs (based on this question):
task generateJavaDocs(type:Javadoc) {
source = 'src/main/java/com'
ext.androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
classpath = files(source) + files(ext.androidJar)
options.memberLevel = JavadocMemberLevel.PUBLIC
include '**/*.java'
exclude '**/BuildConfig.java'
exclude '**/R.java'
}
When reaching this task, Gradle fails with these errors:
/MY_LOCAL_PATH/MyClass.java:5: error: package com.google.gson does not exist
import com.google.gson.Gson;
/MY_LOCAL_PATH/MyClass.java:6: error: package com.google.gson does not exist
import com.google.gson.JsonParseException;
/MY_LOCAL_PATH/MyClass.java:7: error: package com.google.gson does not exist
import com.google.gson.JsonSyntaxException;
/MY_LOCAL_PATH/MyClass.java:8: error: package com.google.gson.reflect does not exist
import com.google.gson.reflect.TypeToken;
Anyone has a thoughts on how to solve this?
Thanks!
I was working on java-library project built with gradle and I had a similar issue with gradle javadocs task:
task javadocs(type: Javadoc) {
source = sourceSets.main.java.srcDirs
exclude '**/R.html', '**/R.*.html', '**/index.html'
}
My library dependency was 'org.json:json:20180130' and my javadocs task was failing with error:
error: package org.json does not exist
I fixed it by adding classpath to javadocs task like this:
task javadocs(type: Javadoc) {
source = sourceSets.main.java.srcDirs
classpath = sourceSets.main.runtimeClasspath
exclude '**/R.html', '**/R.*.html', '**/index.html'
}
If you are working with Android plugin instead of standard java library you can get the classpath like this:
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
I hope this helps someone.