151

I have a custom global class which looks like this

import android.app.Application;

public class MyApp extends Application {

    public String MainAct;

    public String getMainAct() {
        return MainAct;
    }

    public void setMainAct(String mainAct) {
        MainAct = mainAct;
    }
}

I want to preserve a string in this class via another Activity in its onCreate method.

    String local = "myLocalVariable";
    ((MyApp) getApplication()).setMainAct(local); //breaks here!!!
    String name = ((MyApp) getApplication()).getMainAct();

It breaks on the marked line with error: Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.xxx.yyy.global.MyApp

I've checked the code for five times and I cannot find error anywhere. Can anyone tell me where the error is?!

Thanks

sandalone
  • 41,141
  • 63
  • 222
  • 338

2 Answers2

523

The error states that the type of the object returned by getApplication is android.app.Application. A possible cause for this is that you failed to define the application in the manifest. Make sure that your manifest includes something in the lines of:

<application android:name=".MyApp"...
</application>
K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • 35
    Hey. I have this added to my manifest. However, it is still giving me a ClassCastException – Somu Jul 31 '15 at 19:45
  • 15
    Had the same problem minutes ago on Android N, the manifest was correct. Restarted the device - exception was gone. Strange... – artkoenig Oct 16 '16 at 11:50
  • 3
    @Somu clean cache, and close instant run, rebuild project, this worded for me, i think this is a bug of instant run. – LenaYan Oct 21 '16 at 02:47
  • 1
    @artkoenig Thank you for Information! Restart fixed the problem. I was trying to fix this issue. I checked with debugger, `getApplication()` and `getApplicationContext()` could not be casted to my `Application` class. – Ioane Sharvadze Feb 20 '18 at 15:54
18

Another solution for older Android devices or emulators. You defined an application in the manifest:

    <application 
           android:name=".MyApp"...
    </application>

but you still have this problem?

Try to disable instant run:

  1. Disable an Instant run
  2. Clean and rebuild the project
  3. Remove the app from device and install it again without Instant run
Val
  • 4,225
  • 8
  • 36
  • 55