0
我做了一个可以存放应用程序范围变量的类。我把它扩大活动,甚至包括它在清单中,但我仍然收到此错误:无法从android.app.Application转换为自定义类型
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(),但都没有工作
我在做什么错,我该如何解决它。
提前致谢。
您的应用程序必须包含因此您需要从您的清单中删除第二个应用程序节点并将第一个应用程序的名称设置为'GlobalVars' – 2014-09-26 01:21:48
如果您将此作为答案,我会给它一个检查 – user1721803 2014-09-26 01:25:58
您可以检查nPn答案,它的正确的 – 2014-09-26 01:26:45