Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Monday, September 25, 2017

[Android][Resolved] import android.support.design.widget.floatingactionbutton not found

Problem



import android.support.design.widget.FloatingActionButton
Unresolved reference :  design

Solve

Step 1)
Open your build.grade in app level.

Step 2)
Add this lines into dependencies :
compile 'com.android.support:design:25.3.1'
The text in red better if same with your version number of com.android.support:appcompat, for my case, it's com.android.support:appcompat-v7:25.3.1, so i use com.android.support:design:25.3.1.



Step 3)

After edited the file, don't forget to click Sync Now at top-right corner.


Reference

https://stackoverflow.com/questions/38373037/the-import-android-support-design-widget-floatingactionbutton-cannot-be-resolved

Sunday, September 24, 2017

[Android][Resolved] ConstraintLayout element align to bottom-right corner of parent element.

We need to add these 2 lines to the ConstraintLayout element you wanted to be aligned.
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"

Example

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.xxx.wtfapp.MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageButton
        android:id="@+id/btn_create"
        android:background="@android:drawable/ic_menu_more"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"

        android:onClick="addTask"/>

</android.support.constraint.ConstraintLayout>

Reference

https://litotom.com/2016/09/21/android-studio-2-2-constraintlayout/

Tuesday, July 25, 2017

[Android][Solved] Android include layout under app bar

Problem 

Part of the ListView is behind the app bar, and the ListView is placed in another resource file, load with a <include layout="@layout/content_list"/> sentence, the problem shown as this image:

Source code

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_marginTop="?attr/actionBarSize"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.xenialaw.wtfapp.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_list"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/btn_create_task"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Solve

Add the included layout into a FrameLayout and add
android:layout_marginTop="?attr/actionBarSize" as an attribute :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_marginTop="?attr/actionBarSize"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.xxx.wtfapp.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/content"
        android:layout_marginTop="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <include layout="@layout/content_list"/>
    </FrameLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/btn_create_task"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
 Fixed !

Reference

https://stackoverflow.com/questions/32956071/add-views-below-toolbar-in-coordinatorlayout

Wednesday, March 22, 2017

[Android][Resolved] AlertDialog in onOptionsItemSelected() and error : You need to use a Theme.AppCompat theme (or descendant) with this activity

Error Message

11:32:37.946 16933-16933/comps411.tma04.trafficcounter W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x415a7ba8)
01-02 11:32:37.956 16933-16933/comps411.tma04.trafficcounter E/AndroidRuntime: FATAL EXCEPTION: main
Process: comps411.tma04.trafficcounter, PID: 16933
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:310)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:279)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:253)
at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:76)
at android.support.v7.app.AlertController.installContent(AlertController.java:213)
at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:240)
at android.app.Dialog.dispatchOnCreate(Dialog.java:361)
at android.app.Dialog.show(Dialog.java:262)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:902)
at comps411.tma04.trafficcounter.CountingActivity.onOptionsItemSelected(CountingActivity.java:120)
at android.app.Activity.onMenuItemSelected(Activity.java:2600)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:361)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:68)
at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:172)
at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:760)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
at android.support.v7.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:191)
at android.widget.AdapterView.performItemClick(AdapterView.java:299)
at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2911)
at android.widget.AbsListView$3.run(AbsListView.java:3645)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

Source code

Finally found the problem is not much related to the error message: "You need to use a Theme.AppCompat theme (or descendant) with this activity". My case isn't related to adding sth like android:theme="@style/Theme.AppCompat in AndroidManifest.xml suggested from internet exiting case answer.

Do not use getApplicationContext() to get application context for AlertDialog constructor, use this keyword to use activity context :

new AlertDialog.Builder(getApplicationContext())
         .setTitle("Developer")
         .setMessage("Hello")
         .show();

use "this" instead:
new AlertDialog.Builder(this)
         .setTitle("Developer")
         .setMessage("Hello")
         .show(); 

For  further reading, you can click to read the different between application context and activity context: What is different between MainActivity.this vs getApplicationContext()

Reference

http://stackoverflow.com/questions/13143006/alert-dialog-from-within-onoptionsitemselected-android
http://stackoverflow.com/questions/22966601/what-is-different-between-mainactivity-this-vs-getapplicationcontext

Tuesday, March 21, 2017

[Android][Resolved] Android device offline in android studio with windows platform


Version

  • Android Studio 2.2.3
  • Windows 8

Step 1

If your android device is detected but shows offline, you should disconnect your connection to your computer first (Either it's via USB or Wi-Fi)

Step 2 

Close Android Studio.

Step 3

Kill ALL adb.exe processes.
(For example, Press "CTRL"+"ALT"+"DELETE" and then select Task Manager, right click adb.exe and select "End task".)


Step 4

Restart Android Studio

Step5

Restart your Android device and connect it to your computer via USB or wifi. (I use USB cable).

Reference

http://stackoverflow.com/questions/14993855/android-adb-device-offline-cant-issue-commands

Monday, November 7, 2016

[Android][Win8][Resolved] 'adb' is not recognized as an internal or external command, operable program or batch file in windows7 platform

Error message:

'adb' is not recognized as an internal or external command, operable program or batch file.

Thing you had to do is add the Sdk and platform tool of Android to your environment value.

Step1

Look out your Sdk and platform tool of Android first and copy the location. For my case, Android 2.2.2 in windows 8 is located here:
C:\Users\xenialaw\AppData\Local\Android\sdk\platform-tools

Step2

Right click the This PC and select "properties". (In windows 7)

Step3

Select "advanced system settings"

Step4

Click "Environment Variables" button

Step5

Add the location path you copied to the end of Variables value, and then add a semicolon after that.
C:\Users\xxxx\AppData\Local\Android\sdk\platform-tools;
Step6
Restart your android studio or command prompt.

 Reference

http://stackoverflow.com/questions/20564514/adb-is-not-recognized-as-an-internal-or-external-command-operable-program-or

Thursday, November 3, 2016

[Android][Resolved] keytool error: java.io.FileNotFoundException: my-release-key.keystore (Access is denied)

 

Error message :
C:\Program Files\Java\jdk1.8.0_65\bin>keytool -exportcert -alias androiddebugkey
 -keystore ~/.android/debug.keystore -list -v -storepass android
keytool error: java.lang.Exception: Keystore file does not exist: ~/.android/deb
ug.keystore
java.lang.Exception: Keystore file does not exist: ~/.android/debug.keystore
        at sun.security.tools.keytool.Main.doCommands(Main.java:742)
        at sun.security.tools.keytool.Main.run(Main.java:340)
        at sun.security.tools.keytool.Main.main(Main.java:333)
I found answer at stackoverflow by Sarker helps :
http://stackoverflow.com/questions/6602422/access-denied-when-creating-keystore-for-android-app#answer-16386236

Run command with administrator permission:
keytool -genkey -v -keystore C:\Users\YOUR_USERNAME\android_private_key.keystore -alias KeyAlias -keyalg RSA -keysize 2048 -validity 10000
Edit the text in orange to filename you like and the text in green to the location you want save the keystore file.

Beware the target folder must be existed otherwise you may get a java.io.FileNotFoundException, for example:
[Storing d:\my_private_key.keystore]
keytool error: java.io.FileNotFoundException: d:\my_private_key.keystore (The de
vice is not ready)
java.io.FileNotFoundException: d:\my_private_key.keystore (The device is not rea
dy)
        at java.io.FileOutputStream.open0(Native Method)
        at java.io.FileOutputStream.open(FileOutputStream.java:270)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
        at sun.security.tools.keytool.Main.doCommands(Main.java:1141)
        at sun.security.tools.keytool.Main.run(Main.java:340)
        at sun.security.tools.keytool.Main.main(Main.java:333)

Reference:
http://stackoverflow.com/questions/6602422/access-denied-when-creating-keystore-for-android-app

Tuesday, November 1, 2016

[Android][php] Example code for using okhttp to send post repuest and get response from a php webpage

Step1 - Add okhttp as dependencies in yout project

Firstly, you needed to add dependencies your build.gradle in your module and check "Sync Now" next to the line "Gradle files have changed since last project sync. A project sync may be neccessary for the IDE to work properly." with yellow background.


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
}

Step 2 - Create php file

Create a php file named "test.php", for my case i placed it at C:\xampp\htdocs\fcm in windows platform.
<?php
echo "Hello World : ";
if(isset($_POST['test'])) echo $_POST['test'];
?>

Step 3 - Make request and get feedback in your android project

Make request in AsyncTask or Thread, to make it looks simple i put that in a Thread (but using Thread in android may not is the good practice).
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread t = new Thread(new Runnable(){
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                RequestBody body = new FormBody.Builder()
                        .add("test","HAHA")
                        .build(); //Create request body

                Request request = new Request.Builder()
                        .url("http://192.168.232.45/fcm/test.php")
                        .post(body)
                        .build(); //create request

                try {
                    //Send request and save response
                    Response response = client.newCall(request).execute();
                    //Show response
                    Log.d("dump","dump:"+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}

Reference

https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html

[Android][Resolved] remoteMessage.getData().get("message") return null

Source code

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        showNotification("null:"+remoteMessage.getData().get("message"));
    }

    private void showNotification(String message) {
        Intent i = new Intent(this,MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle("FCM Test")
                .setContentText(message)
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0,builder.build());
    }
}

If you get this situation, you can check is the sentence remoteMessage.getData().get("message") return null first, if that's null then use other syntax to get the notification message :
if (remoteMessage.getData().get("message") != null) {
        showNotification( remoteMessage.getData().get("message") );
} else if((remoteMessage.getNotification().getBody() != null)) {
        showNotification( remoteMessage.getNotification().getBody() );
} else {
        Log.d("FCM error","Can receive message but can't get content from FCM");
}

Reference

http://stackoverflow.com/questions/37358462/firebase-onmessagereceived-not-called-when-app-in-background

Monday, October 31, 2016

[Android][Resolved] Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package name 'testing.fcm'

Error message:

Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package name 'testing.fcm'

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fcm.testing.firetest">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>

build.gradlein Module :app

apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    defaultConfig {
        applicationId "testing.fcm"//fcm.testing.firetest
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    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'
    })
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.firebase:firebase-messaging:9.0.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
}
apply plugin: 'com.google.gms.google-services'


Solution : 

Correct the applicationId in defaultConfig and make the value same as build.gradle in Module :app
apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    defaultConfig {
        applicationId "fcm.testing.firetest"
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    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'
    })
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.firebase:firebase-messaging:9.0.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
}
apply plugin: 'com.google.gms.google-services'
And then compile again.

Reference:
http://stackoverflow.com/questions/34679411/android-studio-gradle-errorexecution-failed-for-task-appprocessdebuggoogles , by Hiren

Thursday, October 27, 2016

[Android][Resolved] AdRequest has a private access in 'com.google.android.gms.ads.AdRequest

Message:
C:\Users\xxx\Documents\GitHub\FirebaseTest\app\src\main\java\com\firebasetest\firebasetest\MainActivity.java
Error:(19, 31) error: constructor AdRequest in class AdRequest cannot be applied to given types;
required: Builder
found: no arguments
reason: actual and formal argument lists differ in length
Error:(20, 16) error: cannot find symbol method load(AdRequest)
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
'AdRequest(com.google.android.gms.ads.AdRequest.Builder) has a private access in 'com.google.android.gms.ads.AdRequest'

Check have you used the correct syntax.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Display ads
        mAdView = (AdView) findViewById(R.id.adView);
        //AdRequest adRequest = new AdRequest().Builder().build();
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    }

Reference:

https://www.reddit.com/r/androiddev/comments/36dpun/admob_error_adrequest_has_private_access/

Monday, October 24, 2016

[Tutorial] Firebase Android project push notifications on window platform - part3

Previous article:

[Tutorial] Firebase Android project push notifications on window platform - part1
[Tutorial] Firebase Android project push notifications on window platform - part2

Step13

Select "Notifications" at your menu at firebase console, and then click the button "SEND YOUR FIRST MESSAGE".

Step14

Input textbox under "Message text" is the message you could show to users, in this example let click the arrow next to "Select app" to choose target users.

You should be able to choose your project package name as target:

Step15

 After the target selected, the "SEND MESSAGE" button is activate, let click that:
And then "SEND".

Step 16

Check your Android Emulator, you should be able to found out the message you set in firebase website


Thursday, October 20, 2016

[Android][Resolved] Where is Android keytool in windows platform?

Since keytool is an application provided with standard Java Development Kit (JDK), you should look for it at your Java Home where installed your JDK, for my case, my keytool is installed here:
C:\Program Files\Java\jdk1.8.0_65\bin


You can use that application in command prompt in to generate Certificate fingerprints for development.

If you want know more about Keytool, you can visit this guide:

https://www.digitalocean.com/community/tutorials/java-keytool-essentials-working-with-java-keystores

Reference

http://stackoverflow.com/questions/4830253/where-is-the-keytool-application

Wednesday, October 19, 2016

[Android][Resolved] EmptyThrowable : Invalid Stub element type in index

This case is I am not able to start Android Virtual Device cos the EmptyThrowable Exception: Invalid Stub element type in index.
11:45:03 AM EmptyThrowable
            Invalid stub element type in index:
            file: file://C:/Users/xxx/AppData/Local/Android/sdk/sources/android-24/android/location/OnNmeaMessageListener.java
            psiElement: PsiReferenceList
            requiredClass: interface com.intellij.psi.PsiClass
            actualClass: class com.intellij.psi.impl.source.PsiReferenceListImpl
            virtualFile: size:1342; stamp:0; modCount:1476872314492; fileType:JAVA; language:JAVA
            document: size:1342; stamp:0; committed:true; saved:true
            psiFile: size:1342; stamp:0; class:com.intellij.psi.impl.source.PsiJavaFileImpl; language:JAVA
            stubInfo: created in getStubTree(); with backReference
            indexing info: no data
So first you could do is click "file"-> "Invalidate Caches / Restart" to clear invalidate Caches in your android studion and the restart automatically.



After restarted android studio, you are still not able to run Android Virtual Device, let look for any update available for your android studio:



For my case, i updated my Android studio to latest version 2.2.2, ran Android Virtual Device (AVD) for the project and it's not work again, just follow the instruction to download the missing system image :

And finally it works .

Reference

http://www.voidcn.com/blog/louisyonge/article/p-4936383.html

Monday, October 17, 2016

[Android][Firebase][Resolved] Firebase API initialization failure.

During compiling an Android project with firebase, get an "Firebase API initialization failure" error,  the java.lang.reflect.InvocationTargetException.

Full error message :
10-19 03:14:36.911 3039-3039/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-19 03:14:36.911 3039-3039/? E/android.os.Debug: failed to load memtrack module: -2
10-19 03:14:38.435 3071-3071/? E/memtrack: Couldn't load memtrack module (No such file or directory)
10-19 03:14:38.435 3071-3071/? E/android.os.Debug: failed to load memtrack module: -2
10-19 03:14:38.536 3084-3084/? A/FirebaseApp: Firebase API initialization failure.
                                              java.lang.reflect.InvocationTargetException
                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                  at java.lang.reflect.Method.invoke(Method.java:372)
                                                  at com.google.firebase.FirebaseApp.zza(Unknown Source)
                                                  at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                  at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                  at com.google.firebase.FirebaseApp.zzbu(Unknown Source)
                                                  at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                                                  at android.content.ContentProvider.attachInfo(ContentProvider.java:1696)
                                                  at android.content.ContentProvider.attachInfo(ContentProvider.java:1671)
                                                  at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                                                  at android.app.ActivityThread.installProvider(ActivityThread.java:4999)
                                                  at android.app.ActivityThread.installContentProviders(ActivityThread.java:4594)
                                                  at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4534)
                                                  at android.app.ActivityThread.access$1500(ActivityThread.java:151)
                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
                                                  at android.os.Handler.dispatchMessage(Handler.java:102)
                                                  at android.os.Looper.loop(Looper.java:135)
                                                  at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                  at java.lang.reflect.Method.invoke(Method.java:372)
                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                               Caused by: java.lang.IncompatibleClassChangeError: The method 'java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)' was expected to be of type virtual but instead was found to be of type direct (declaration of 'java.lang.reflect.ArtMethod' appears in /system/framework/core-libart.jar)
                                                  at com.google.firebase.iid.zzg.zzeC(Unknown Source)
                                                  at com.google.firebase.iid.zzg.<init>(Unknown Source)
                                                  at com.google.firebase.iid.zzg.<init>(Unknown Source)
                                                  at com.google.firebase.iid.zzd.zzb(Unknown Source)
                                                  at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                  at java.lang.reflect.Method.invoke(Method.java:372)
                                                  at com.google.firebase.FirebaseApp.zza(Unknown Source)
                                                  at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                  at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                  at com.google.firebase.FirebaseApp.zzbu(Unknown Source)
                                                  at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                                                  at android.content.ContentProvider.attachInfo(ContentProvider.java:1696)
                                                  at android.content.ContentProvider.attachInfo(ContentProvider.java:1671)
                                                  at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                                                  at android.app.ActivityThread.installProvider(ActivityThread.java:4999)
                                                  at android.app.ActivityThread.installContentProviders(ActivityThread.java:4594)
                                                  at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4534)
                                                  at android.app.ActivityThread.access$1500(ActivityThread.java:151)
                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
                                                  at android.os.Handler.dispatchMessage(Handler.java:102)
                                                  at android.os.Looper.loop(Looper.java:135)
                                                  at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                  at java.lang.reflect.Method.invoke(Method.java:372)
                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
10-19 03:14:38.636 3084-3084/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.firebase.pushnotification, PID: 3084
                                                 java.lang.IncompatibleClassChangeError: The method 'java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)' was expected to be of type virtual but instead was found to be of type direct (declaration of 'java.lang.reflect.ArtMethod' appears in /system/framework/core-libart.jar)
                                                     at com.google.firebase.iid.zzg.zzeC(Unknown Source)
                                                     at com.google.firebase.iid.zzg.<init>(Unknown Source)
                                                     at com.google.firebase.iid.zzg.<init>(Unknown Source)
                                                     at com.google.firebase.iid.zzd.zzb(Unknown Source)
                                                     at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                                                     at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                                                     at com.google.firebase.messaging.FirebaseMessaging.getInstance(Unknown Source)
                                                     at com.firebase.pushnotification.MainActivity.onCreate(MainActivity.java:16)
                                                     at android.app.Activity.performCreate(Activity.java:5990)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
10-19 03:14:38.693 708-708/? E/EGL_emulation: tid 708: eglCreateSyncKHR(1209): error 0x3004 (EGL_BAD_ATTRIBUTE)
According to samtstern in github.com, trying to update your dependency from compile 'com.google.firebase:firebase-messaging:9.0.0' to compile 'com.google.firebase:firebase-messaging:9.0.2' can fix this. And i tried it works like a claim:

my module/build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.firebase.pushnotification"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'

    apply plugin: 'eclipse'
    //compile 'com.google.firebase:firebase-messaging:9.0.0'
    compile 'com.google.firebase:firebase-messaging:9.0.2'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
}

apply plugin: 'com.google.gms.google-services'

Other files in my testing project for your reference:
my project/build.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:1.5.0'
        classpath 'com.google.gms:google-services:3.0.0'
        // 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
}
 Reference:
https://github.com/firebase/quickstart-android/issues/24