androidandroid-application-class

Error: incompatible types: Application cannot be converted to AnalyticsApplication.: Android Studio 2.3.2


I updated my Android Studio to 2.3.2 after which the gradle build fails with the below error:

error: incompatible types: Application cannot be converted to AnalyticsApplication.

I have tried searching about it but could not find anything relevant.

The build.gradle file:

android {
  compileSdkVersion 25
  buildToolsVersion "25.0.2"

defaultConfig {
    applicationId "com.xxx.xxx"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 17
    versionName "1.6.7"
    multiDexEnabled true
}

I am getting error here,

        // Obtain the shared Tracker instance.
        AnalyticsApplication application = (AnalyticsApplication) getApplication();
        mTracker = application.getDefaultTracker();

        sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(context);
        sharedPrefsEditor = sharedPrefs.edit();

        defineFields();

    } catch (Exception e) {
        e.printStackTrace();
    }

AnalyticApplication.java:

import android.app.Application;
import android.support.multidex.MultiDexApplication;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

 /**
 * This is a subclass of {@link Application} used to provide shared          objects for this app, such as the {@link Tracker}.*/
    public class AnalyticsApplication extends MultiDexApplication {
    private Tracker mTracker;

    /**
     * Gets the default {@link Tracker} for this {@link Application}.
     * @return tracker
     */
    synchronized public Tracker getDefaultTracker() {
    if (mTracker == null) {
        GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
        // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
        mTracker = analytics.newTracker(R.xml.global_tracker);
     }
        return mTracker;
    }
}

Solution

  • I can see that you have used

    import android.support.multidex.MultiDexApplication;
    

    As you specifically mentioned being updated the studio version to 2.3, I suggest you have a look to Getting "package android.support.multidex does not exist" after upgrading to Android Studio 2.3

    I am not quite sure but this could be the solution to your problem as I myself was having a similar issue after the studio upgrade. Hope it helps you.