我做了一个可以容纳应用程序范围变量的类。我进行了扩展活动,甚至将其包括在清单中,但仍然出现此错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.blacksmith/com.example.blacksmith.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.blacksmith.GlobalVars
这是课程:
package com.example.blacksmith;
import android.app.Application;
public class GlobalVars extends Application {
private Boolean DefaultEncrypt;
private String Password;
public GlobalVars(){
DefaultEncrypt = true;
}
public void setDefaultEncrypt(Boolean is){
DefaultEncrypt = is;
}
public Boolean getDefaultEncrypt(){
return DefaultEncrypt;
}
public void setPassword(String pass){
Password = pass;
}
public String getPassword(){
return Password;
}
}
这是android清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.blacksmith"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="Blacksmith"
android:theme="@android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".PasswordCreatorActivity"
android:label="@string/title_activity_password_creator" >
</activity>
<activity
android:name=".LoginActivity"
android:label="@string/title_activity_login" >
</activity>
</application>
<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:name=".application.GlobalVars">
</application>
</manifest>
这是我访问它的方式:
GlobalVars tmp = ((GlobalVars) getApplicationContext());
tmp.setDefaultEncrypt(sharedPref.getBoolean("Default", true));
tmp.setPassword(sharedPref.getString("password", "0x1234"));
注意:我尝试了this.getApplication()和getApplication(),但都没有用
我在做什么错以及如何解决。
提前谢谢。
最佳答案
我不确定100%,但是您有2个应用程序节,请尝试移动/替换以下项目:
<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:name=".application.GlobalVars">
</application>
到您的原始应用程序节中:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name=".application.GlobalVars"
>
<activity
android:name=".MainActivity"
android:label="Blacksmith"
android:theme="@android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".PasswordCreatorActivity"
android:label="@string/title_activity_password_creator" >
</activity>
<activity
android:name=".LoginActivity"
android:label="@string/title_activity_login" >
</activity>
</application>