I am new to android and in a process of adding google analytics to one of my application. I am getting the following error when running my application.
android.app.Application cannot be cast to com.xxx.xxx.xxx.AnalyticsApplication
This is my main activity.
package com.example.dell.testanalytics;
import android.content.Intent;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Logger;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Tracker mTracker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// [START screen_view_hit]
String name = getString(R.string.test);
Log.i(TAG, "Setting screen name: " + name);
mTracker.setScreenName("Image~" + name);
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
// [END screen_view_hit]
return false;
}
}
The error is pointing the place I call the analytics application method.
This is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I cannot figure out what is wrong since i am not getting any errors or red lines in the code.
Would be great if i could get your assistance.
If you wish to replace the singleton
Application
instance with some subclass ofApplication
, you need to have theandroid:name
attribute of the<application>
element of your manifest point to that subclass.Well I believe everything answered ahead of me is true but it is more important where you place the
android:name
attribute. Do this in your manifest<application android:name="com.yourwebsite.appname.SubApplication" >...</application>
NOT
Also do not add any more
<application>
tags use your original one!!