Problem with Google Maps: java.lang.ClassCastException: android.app.Application can not be cast to android.app.Activity

1

I am practicing with the example of a videoturorial, I have reviewed the code several times, but the application does not work, in the video tutorial if it is seen to work, but when I show the map the application closes.

I try to see the operation of this code to see if I can then change it to put the map I have created in an HTML file.

this is code that I have put:

AndroidManifest.xml

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <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: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>

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps"></activity>
    </application>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Button ubicarme;

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

        ubicarme=(Button)findViewById(R.id.ubicarme);

        ubicarme.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                Intent intent =new Intent(MainActivity.this,MapsActivity.class);
                startActivity(intent);
            }
        });

    }
}

MapsActivity.java

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

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

        int status= GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
        if (status== ConnectionResult.SUCCESS){

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }else {
            Dialog dialog=GooglePlayServicesUtil.getErrorDialog(status,(Activity) getApplicationContext(),10);
            dialog.show();
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        UiSettings uiSettings=mMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(true);

        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Hola").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        float zoomlevel=16;
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,zoomlevel)); 
    }
}

Not if I have to put some more data so that you can see where the application fails.

Error showing

12/29 18:41:50: Launching app
$ adb push C:\Users\SoCu\AndroidStudioProjects\googlemaps\app\build\outputs\apk\debug\app-debug.apk /data/local/tmp/com.example.codigofacilito.googlemaps
$ adb shell pm install -t -r "/data/local/tmp/com.example.codigofacilito.googlemaps"
Success


$ adb shell am start -n "com.example.codigofacilito.googlemaps/com.example.codigofacilito.googlemaps.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Waiting for process to come online
Waiting for process to come online
Waiting for process to come online
Connected to process 3642 on device Nexus_5X_API_27_x86 [emulator-5554]
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/zygote: Not late-enabling -Xcheck:jni (already on)
W/zygote: Unexpected CPU variant for X86 using defaults: x86
E/zygote: Failed sending reply to debugger: Broken pipe
I/zygote: Debugger is no longer active

          [ 12-29 17:42:05.477  1597: 1644 D/         ]
          HostConnection::get() New Host Connection established 0x92b27040, tid 1644
D/OpenGLRenderer: HWUI GL Pipeline
I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0xab005120: maj 3 min 1 rcv 4
D/EGL_emulation: eglMakeCurrent: 0xab005120: ver 3 1 (tinfo 0xab003290)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
D/EGL_emulation: eglMakeCurrent: 0xab005120: ver 3 1 (tinfo 0xab003290)
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 11910000 but found 11580470
I/chatty: uid=10090(com.example.codigofacilito.googlemaps) identical 8 lines
W/GooglePlayServicesUtil: Google Play services out of date.  Requires 11910000 but found 11580470
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.codigofacilito.googlemaps, PID: 3642
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.codigofacilito.googlemaps/com.example.codigofacilito.googlemaps.MapsActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                      at android.os.Handler.dispatchMessage(Handler.java:106)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                   Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
                      at com.example.codigofacilito.googlemaps.MapsActivity.onCreate(MapsActivity.java:35)
                      at android.app.Activity.performCreate(Activity.java:6999)
                      at android.app.Activity.performCreate(Activity.java:6990)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
                      at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
                      at android.os.Handler.dispatchMessage(Handler.java:106) 
                      at android.os.Looper.loop(Looper.java:164) 
                      at android.app.ActivityThread.main(ActivityThread.java:6494) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

Thank you.

    
asked by SoCu 28.12.2017 в 15:25
source

1 answer

1

The problem is generated in this line:

Dialog dialog=GooglePlayServicesUtil.getErrorDialog(status,(Activity) getApplicationContext(),10);

and it is caused because you are trying to cast the context as Activity, it is defined as:

  

java.lang.ClassCastException: android.app.Application can not be cast   to android.app.Activity

Application is not a subclass of Activity , so if you are inside an activity you can get the context of it in this way using this :

Dialog dialog=GooglePlayServicesUtil.getErrorDialog(status,this,10);
    
answered by 29.12.2017 / 18:34
source